List 在返回列表之前,如何在Ocaml中记录列表的所有元素?
我想记录(现在打印)结果中的所有元素,然后再减少返回。有没有办法做到这一点List 在返回列表之前,如何在Ocaml中记录列表的所有元素?,list,ocaml,List,Ocaml,我想记录(现在打印)结果中的所有元素,然后再减少返回。有没有办法做到这一点 let calculate ~size_of_experiment:s ~number_of_buckets:n = let results = run_experiments s n in List.iter (fun x -> print_endline x) results; List.fold_left (fun x y -> x + (snd y)) 0 results 上述代码无法编
let calculate ~size_of_experiment:s ~number_of_buckets:n =
let results = run_experiments s n in
List.iter (fun x -> print_endline x) results;
List.fold_left (fun x y -> x + (snd y)) 0 results
上述代码无法编译:
Error: This expression has type (int * int) list
but an expression was expected of type string list
Type int * int is not compatible with type string
您唯一的问题似乎是列表中的元素属于
(int*int)
类型,您将它们视为字符串
let string_of_int_pair (a, b) = Printf.sprintf "(%d, %d)" a b
let calculate ~size_of_experiment:s ~number_of_buckets:n =
let results = run_experiments s n in
List.iter (fun x -> print_endline (string_of_int_pair x)) results;
List.fold_left (fun x y -> x + (snd y)) 0 results
更普遍的问题是,如果有一种方法可以打印各种类型的值,而不必为每种情况自己编写代码,那就太好了。为此,您可以使用类似的工具。谢谢@jeffrey我完全忘记了关于Ocaml的这个细节。