如何在返回列表之前记录Ocaml中列表的所有元素?

问题描述:

我想记录(现在打印)结果中的所有元素,然后减少它以返回。有没有办法实现这一点?如何在返回列表之前记录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 

上面的代码无法编译:

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 

更常见的问题是,如果不用为每个案例编写代码,就有办法打印各种类型的值将会非常好。为此,你可以使用类似deriving的东西。

+0

谢谢@jeffrey我完全忘记了关于Ocaml的这个细节。 – Istvan