|
|
# OCaml as she is wrote |
|
|
|
|
|
|
|
OCaml is not a mainstream language, and the syntax and semantics you |
|
|
|
are used to from more conventional languages may not work. This page |
|
|
|
acts as a phrase book explaining how to translate idioms from more |
|
|
|
common languages to OCaml. |
|
|
|
|
|
|
|
## If you know how to do this in Standard ML |
|
|
|
|
|
|
|
fun fact n = if n = 0 then 1 else n * fact (n-1) |
|
|
|
|
|
|
|
### Then do it like this in OCaml |
|
|
|
|
|
|
|
let rec fact n = match n with |
|
|
|
| 0 -> 1 |
|
|
|
| n -> n * (fact (n - 1)) |
|
|
|
|
|
|
|
## If you know how to do this in APL |
|
|
|
|
|
|
|
fact←{×/⍳⍵} |
|
|
|
|
|
|
|
### Then do it like this in OCaml |
|
|
|
|
|
|
|
let rec fact n = match n with |
|
|
|
| 0 -> 1 |
|
|
|
| n -> n * (fact (n - 1)) |
|
|
|
|
|
|
|
## If you know how to do this in Brainfuck |
|
|
|
|
|
|
|
[->+<]>[[>+>+<<-]>>-<[-<+>]>[-<+>]<]<[->+<]< |
|
|
|
[[->>[-<+>>+<]>[-<+>]<<<]>>[-]<<<]>>[-<<+>>]<< |
|
|
|
|
|
|
|
### Then do it like this in OCaml |
|
|
|
|
|
|
|
let rec fact n = match n with |
|
|
|
| 0 -> 1 |
|
|
|
| n -> n * (fact (n - 1)) |
|
|
|
|
|
|
|
## If you know how to do this in Futhark |
|
|
|
|
|
|
|
def fact n = reduce (*) 1 (iota n) |
|
|
|
|
|
|
|
### Then do it like this in OCaml |
|
|
|
|
|
|
|
let rec fact n = match n with |
|
|
|
| 0 -> 1 |
|
|
|
| n -> n * (fact (n - 1)) |
|
|
|
|
|
|
|
## If you know how to do this in Emacs Lisp |
|
|
|
|
|
|
|
(defun fact (n) (if (= n 0) 1 (* n (fact (- n 1))))) |
|
|
|
|
|
|
|
### Then do it like this in OCaml |
|
|
|
|
|
|
|
let rec fact n = match n with |
|
|
|
| 0 -> 1 |
|
|
|
| n -> n * (fact (n - 1)) |
|