Overview of OCaml
From website: https://cs3110.github.io/textbook/chapters/basics/functions.html
Basic Knowledge
“A language that doesn’t affect the way you think about programming is not worth knowing.” — Alan J. Perlis (1922-1990), first recipient of the Turing Award
Why OCaml?
- Immutability
- Abstraction
- Type System
Expressions
1 | (* - : int = 6 *) |
Recursive Functions
Recursive functions are defined like this:let rec f x = ...
Mutually recursive functions can be defined with the and keyword:
1 | let rec f x1 ... xn = e1 |
For example:
1 | (** [even n] is whether [n] is even. |
Anonymous Functions
OCaml functions do not have to have names; they may be anonymous.
For example, here is an anonymous function that increments its input: fun x -> x + 1
.
Pipeline
1 | func @@ 2 * 10;; |
Labeled and Optional Arguments
let f ~name1:arg1 ~name2:arg2 = arg1 + arg2;;
let f ?name:(arg1=8) arg2 = arg1 + arg2
Use: f ~name:1 2;;
We can even define our own new infix operators, for example:
let ( ^^ ) x y = max x y
Tail Recursion
A recursive call in tail position does not need a new stack frame.
It can just reuse the existing stack frame.
Module
OCaml | |
---|---|
NameSpaces | Structure |
Interfaces | Signature |
Encapsulation | Abstract Types |
Code Reuse | Functors, include |
Overview of OCaml