Grammar
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| 65 / 60
65 mod 60
3.14 *. 2. 1.0 +. 2.0
&& || = <> ==, !=
"abc" ^ "d" "abc".[1]
string_of_int 42 int_of_string "43"
let () = assert (f x = y)
if ... then ... else if ... then ... else ...
let x = 42 in x+1
e1; e2; e3
(ignore e1); e2
|
Functions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| let f x = ...
let rec f x = ...
let inc = fun x -> x + 1
f (g x)
x |> g |> f
f ~name1:arg1 ~name2:arg2 = arg1+arg2
f ~name1 ~name2 = name1 + name2
f ?name1:(arg1=8) arg2 = arg1 + arg2
f ~name1:3 ~name2:4
|
可以这样认为:每一个 OCaml function 都只接受一个参数,多参数的函数可以看作是 x -> (some other function) 例如
1 2 3
| t1 -> t2 -> t3 -> t4
t1 -> (t2 -> (t3 -> t4))
|
因此,函数本质是 right associative 的.
但是,函数调用是 left associative 的,e1 e2 e3 e4 会被解释为 ((e1 e2) e3) e4
Documentation
用 (** ... *) 表示文档,用方括号包起来 [] 以 monospace 字体显示,同时也有 @param 等等解释性 tag,以及 Raises:, Requires: 的解释性标签.
Printing
1 2 3
| Printf.printf "%s: %F\n%!" name num
|
Debugging
可以在解释器界面用 #trace fib 的方式检查中间输出,或者用 ocamldebug 程序.