在OCaml中打印列表列表

时间:2015-03-13 01:55:16

标签: recursion 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);;

我知道这是错的,但我无法找到办法。

1 个答案:

答案 0 :(得分:1)

这是一种方法:

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只会将图片转换为字符串并打印结果。

相关问题