在 OCaml 中打印列表列表
Printing a list of lists in OCaml
所以我正在尝试打印如下所示的列表列表:
[0;0;0;0;0];
[0;0;0;0;0];
[0;0;1;0;0];
[0;0;0;0;0];
我可以根据需要使用尽可能多的功能,但只有一个功能可以使用打印功能。这是我目前所拥有的:
let rec rowToString(row) =
if (row == []) then []
else string_of_int(List.hd row) :: ";" :: rowToString(List.tl row);;
let rec pp_my_image s =
print_list(rowToString(List.hd s)) :: pp_my_image(List.tl s);;
我知道这是错误的,但我想不出办法。
这是一种方法:
let rec rowToString r =
match r with
| [] -> ""
| h :: [] -> string_of_int h
| h :: t -> string_of_int h ^ ";" ^ (rowToString t)
let rec imageToString i =
match i with
| [] -> ""
| h :: t -> "[" ^ (rowToString h) ^ "];\n" ^ (imageToString t)
let pp_my_image s =
print_string (imageToString s)
rowToString
函数将创建一个字符串,其中包含每个内部列表中的项目。请注意,大小写 h :: []
是分开的,因此不会在最后一项之后添加分号。
imageToString
函数将调用 rowToString
为每个内部列表创建一个字符串。它将用方括号括起每个字符串的结果,并在末尾添加分号和换行符。
pp_my_image
会将图像简单地转换为字符串并打印结果。
所以我正在尝试打印如下所示的列表列表:
[0;0;0;0;0];
[0;0;0;0;0];
[0;0;1;0;0];
[0;0;0;0;0];
我可以根据需要使用尽可能多的功能,但只有一个功能可以使用打印功能。这是我目前所拥有的:
let rec rowToString(row) =
if (row == []) then []
else string_of_int(List.hd row) :: ";" :: rowToString(List.tl row);;
let rec pp_my_image s =
print_list(rowToString(List.hd s)) :: pp_my_image(List.tl s);;
我知道这是错误的,但我想不出办法。
这是一种方法:
let rec rowToString r =
match r with
| [] -> ""
| h :: [] -> string_of_int h
| h :: t -> string_of_int h ^ ";" ^ (rowToString t)
let rec imageToString i =
match i with
| [] -> ""
| h :: t -> "[" ^ (rowToString h) ^ "];\n" ^ (imageToString t)
let pp_my_image s =
print_string (imageToString s)
rowToString
函数将创建一个字符串,其中包含每个内部列表中的项目。请注意,大小写 h :: []
是分开的,因此不会在最后一项之后添加分号。
imageToString
函数将调用 rowToString
为每个内部列表创建一个字符串。它将用方括号括起每个字符串的结果,并在末尾添加分号和换行符。
pp_my_image
会将图像简单地转换为字符串并打印结果。