OCaml中List.iter和List.map函数之间的区别

vik*_*k-y 5 ocaml functional-programming

我遇到了这个功能:List.map.我所理解的是List.map将函数和列表作为参数并转换列表中的每个元素.

List.iter 做类似的事情(也许?),参考下面的例子:

# let f elem =
Printf.printf "I'm looking at element %d now\n" elem in
List.iter f my_list;;
I'm looking at element 1 now
I'm looking at element 2 now
I'm looking at element 3 now
I'm looking at element 4 now
I'm looking at element 5 now
I'm looking at element 6 now
I'm looking at element 7 now
I'm looking at element 8 now
I'm looking at element 9 now
I'm looking at element 10 now
- : unit = ()
Run Code Online (Sandbox Code Playgroud)

有人可以解释之间的差异List.mapList.iter

注意:我是OCaml和函数式编程的新手.

Jef*_*eld 9

List.map返回根据调用提供的函数的结果形成的新列表.List.iter只是回归(),这是一个特别无趣的价值.也就是说,List.iter当你只想调用一个不会返回任何有趣内容的函数时.在您的示例中,Printf.printf实际上不会返回有趣的值(它返回()).

请尝试以下方法:

List.map (fun x -> x + 1) [3; 5; 7; 9]
Run Code Online (Sandbox Code Playgroud)


use*_*453 5

杰弗里已经相当彻底地回答了这个问题,但是我想详细说明一下。

List.map接受一种类型的列表,然后一次将每个值通过一个函数放入一个函数,并用这些结果填充另一个列表,因此运行List.map (string_of_int) [1;2;3]等效于以下内容:

[string_of_int 1; string_of_int 2; string_of_int 3]
Run Code Online (Sandbox Code Playgroud)

List.iter另一方面,当您只需要函数的副作用时(例如let s = ref 0 in List.iter (fun x -> s := !s + x) [1;2;3],或在代码中给出的示例),应使用。

总之,使用List.map的时候你想看到的东西做每个元素在列表中,使用List.iter的时候你想看到的东西做列表中的每个元素。