2016-03-02 84 views
2

我碰到過這個函數:List.map。我所理解的是List.map將函數和列表作爲參數並轉換列表中的每個元素。OCaml中List.iter和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 =() 

的例子有人可以解釋List.mapList.iter之間的區別?

注:我是OCaml和函數式編程的新手。

回答

4

List.map返回由調用提供的函數的結果形成的新列表。 List.iter只是返回(),這是一個特別無趣的值。也就是說,當你只想調用一個不會返回任何有趣的函數時,這個函數就是用於這個函數的。在你的例子中,Printf.printf實際上並沒有返回一個有趣的值(它返回())。

嘗試以下操作:

List.map (fun x -> x + 1) [3; 5; 7; 9] 
+0

明白了。謝謝。 –

2

傑弗裏已經相當徹底地回答了這個問題,但我想闡述一下就可以了。

List.map採用一個類型的列表,並在同一時間使其每個值的通過函數之一,並填充與這些結果另一個列表,因此運行List.map (string_of_int) [1;2;3]是等效於以下:

[string_of_int 1; string_of_int 2; string_of_int 3] 

List.iter另一方面,當你只需要函數的副作用時(例如let s = ref 0 in List.iter (fun x -> s := !s + x) [1;2;3],或者你在代碼中給出的例子),應該使用它。

綜上所述,使用List.map當你想看到的東西在列表中進行每個元素,使用List.iter當你想看到的東西在列表中進行每個元素。