假设
type house = {first_name: string; last_name: string; nb_windows: int; nb_doors: int; nb_cars: int; nb_rooms: int};;
house1 = {first_name="John"; last_name="Doe; nb_windows = 10; nb_doors = 50; nb_cars = 3; nb_rooms= 10};;
我要打印记录house1
的每个元素。
Full Name : John Doe
Number of windows : 10
Number of doors : 50
Number of cars : 3
Number of rooms : 10
我定义函数的方法是
let test (lch: house) =
begin
print_string ("Full Name : " ^ lch.first_name ^ " " ^ lch.last_name "\n");
print_string ("Number of windows : " ^ string_of_int lch.nb_windows ^ "\n");
print_string ("Number of doors : " ^ string_of_int lch.nb_doors ^ "\n");
print_string ("Number of car : " ^ string_of_int lch.nb_cars ^ "\n");
print_string ("Number of rooms : " ^ string_of_int lch.nb_rooms ^ "\n\n");
end;;
test house1;;
但是,该功能非常有限。例如,如果我定义
house2 = {first_name=""; last_name="" nb_windows=10; nb_doors = 50; nb_cars = 3; nb_rooms= 10}
在该示例中,如果Full Name
和first_name
为空字符串,我不想打印last_name
。>
如何修改test
功能,以便仅显示test house2;;
行
Number of windows : 10 Number of doors : 50 Number of cars : 3 Number of rooms : 10
而不是
Full Name : Number of windows : 10 Number of doors : 50 Number of cars : 3 Number of rooms : 10
请注意,我只需要使用功能范式,因此没有
while
或for
循环。
答案的开头
我想我可以使用类似的东西
let print_data x y = match x with | "" -> () | x -> print_string y;;
但我不知道如何继续前进
假设类型为house = {first_name:string; last_name:字符串; nb_windows:int; nb_doors:int; nb_cars:int; nb_rooms:int} ;; house1 = {first_name =“ John”; last_name =“ Doe; nb_windows = 10; nb_doors = ...
您的函数print_data
测试一个字符串以确定是否打印另一个字符串。如果将lch.first_name ^ lch.last_name
作为测试字符串,并将所需的输出字符串作为第二个字符串,则可以使用此函数。