Add anonymous functions and list map/filter sections to the OCaml tutorial.

This commit is contained in:
Daniil Baturin 2014-09-13 00:54:23 +07:00
parent 807a958c78
commit 5cf408a7a9

View File

@ -150,6 +150,8 @@ x + y ;;
works for non-recursive definitions too. *) works for non-recursive definitions too. *)
let a = 3 and b = 4 in a * b ;; let a = 3 and b = 4 in a * b ;;
(* Anonymous functions use the following syntax: *)
let my_lambda = fun x -> x * x ;;
(*** Operators ***) (*** Operators ***)
@ -207,6 +209,10 @@ let bad_list = [1, 2] ;; (* Becomes [(1, 2)] *)
(* You can access individual list items with the List.nth function. *) (* You can access individual list items with the List.nth function. *)
List.nth my_list 1 ;; List.nth my_list 1 ;;
(* There are higher-order functions for lists such as map and filter. *)
List.map (fun x -> x * 2) [1; 2; 3] ;;
List.filter (fun x -> if x mod 2 = 0 then true else false) [1; 2; 3; 4] ;;
(* You can add an item to the beginning of a list with the "::" constructor (* You can add an item to the beginning of a list with the "::" constructor
often referred to as "cons". *) often referred to as "cons". *)
1 :: [2; 3] ;; (* Gives [1; 2; 3] *) 1 :: [2; 3] ;; (* Gives [1; 2; 3] *)