let a_tuple = (3,"tree");; let b_tuple = (3,"four",5.);; let x,y,z = b_tuple;;
1 2 3 4 5 6 7 8
# let a_tuple = (3,"tree");; val a_tuple : int * string = (3, "tree") # let b_tuple = (3,"four",5.);; val b_tuple : int * string * float = (3, "four", 5.) # let x,y,z = b_tuple;; val x : int = 3 val y : string = "four" val z : float = 5.
列表可以保存任意数目相同类型的元素。注意使用分号,不然会当作是一个元组作元素的单元素列表,如下:
1 2
let languages = ["OCaml","Perl","C"];; let languages = ["OCaml";"Perl";"C"];;
1 2 3 4
# let languages = ["OCaml","Perl","C"];; val languages : (string * string * string) list = [("OCaml", "Perl", "C")] # let languages = ["OCaml";"Perl";"C"];; val languages : string list = ["OCaml"; "Perl"; "C"]
# "test"::languages;; - : string list = ["test"; "OCaml"; "Perl"; "C"] # "test"::[];; - : string list = ["test"] # [1;2;3];; - : int list = [1; 2; 3] # 1::(2::(3::[]));; - : int list = [1; 2; 3] # 1::2::3::[];; - : int list = [1; 2; 3]
列表的模式匹配,注意模式不完备问题,使用 match 语句。
1 2 3 4 5 6 7 8 9
(* 列表的模式匹配 *) let my_favorite_language (my_favorite :: the_rest) = my_favorite;; let my_favorite_language my_favorite = match my_favorite with | first :: the_rest -> first | [] -> "None";; my_favorite_language [];; my_favorite_language ["English";"Math"];;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# let my_favorite_language (my_favorite :: the_rest) = my_favorite;; Characters 25-66: .........................(my_favorite :: the_rest) = my_favorite.. Warning 8: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: [] val my_favorite_language : 'a list -> 'a = <fun> # let my_favorite_language my_favorite = match my_favorite with | first :: the_rest -> first | [] -> "None";; val my_favorite_language : string list -> string = <fun> # my_favorite_language [];; - : string = "None" # my_favorite_language ["English";"Math"];; - : string = "English"
递归列表函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
(* 递归列表函数 *) letrec sum l = match l with | [] -> 0(* 基本情况 *) | hd::tl -> hd + sum tl;; (* 归纳情况 *)
letrec sum_length l = match l with | [] -> 0(* 基本情况 *) | hd :: tl -> String.length hd + sum_length tl;; (* 归纳情况 *)
sum [5;4;3;2];; sum [];; sum_length ["What";"tes";"ab";"1"];; sum_length [];;
# let rec sum l = match l with | [] -> 0 (* 基本情况 *) | hd::tl -> hd + sum tl;; val sum : int list -> int = <fun> # let rec sum_length l = match l with | [] -> 0 (* 基本情况 *) | hd :: tl -> String.length hd + sum_length tl;; val sum_length : Core.Std.String.t list -> int = <fun> # sum [5;4;3;2];; - : int = 14 # sum [];; - : int = 0 # sum_length ["What";"tes";"ab";"1"];; - : int = 10 # sum_length [];; - : int = 0 # sum_length [];; - : int = 0