Ken Wakita (https://wakita.github.io/fp2018/)
Oct. 1, 2018
The prompt: #
The termination mark: ;;
Constants and functions are defined by let
Recursive functions are defined by let rec (e.g., fib)
bool, char, float, int, string
1 and 1.0 are different+ vs +. are different.
So are - vs -., * vs *., and / vs /..
[], [a; b; c]
let is_beautiful = ["is"; "beautiful"]
"Life" :: is_beautiful
is_beautiful @ is_beautiful
Multiple parts of a list can be retrieved by a pattern match.
An arbitrary expression is allowed for the result of pattern matching: e.g. (a + b + c, rest).
# match [1; 2; 3; 4; 5] with
a :: b :: c :: rest -> (a + b + c, rest);;
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(_::_::[]|_::[]|[])
- : int * int list = (6, [4; 5])a = 1, b = 2, c = 3, rest = [4, 5] and computes a + b + c = 6 and pairs this result with the value of rest.Why OCaml keeps alerting us with Warning?
OCaml presents anti-patterns, like _::_::[], _::[], [], for the last example.
Fix is easy. Just deal with anti-patterns.
# match [1; 2; 3; 4; 5] with
a :: rest -> a
| _ -> raise (Failure("Can't get value out of an empty list."));;
- : int = 1
# match [1; 2; 3; 4; 5] with
a :: b :: c :: rest -> (a + b + c, rest)
| _ -> raise (Failure("I don't care about short lists"))
- : int * int list = (6, [4; 5])a :: rest and [] in the first example.let rec f x = ... and g y = ... and ... syntax.A touple can group together values of different types.
# let data = ('I', "have", 2, "apples");;
val data : char * string * int * string = ('I', "have", 2, "apples")Use pattern matching to retrieve elements from the tuple:
_[| |]A triple array: [| 1.0; 2.0; 4.0 |]
A string array: let beautiful = [| "is"; "beautiful" |]
beautiful.(0) <- "are"beautiful.(0) → "are"| Arrays | Lists | |
|---|---|---|
| Elements modification | Mutable | Immutable |
| Size | Fixed | Can grow with :: |
| Accessing Elements | O(1) for every element | O(1) for the head, O(n) in average |
\[\frac {\mathrm {d} f} {\mathrm {d} x} (x) = \lim_{\Delta x \rightarrow 0} \frac {f(x + \Delta x) - f(x)} {\Delta x}\]
\[(f \circ g)(x) = f(g(x))\]
The let f x y z syntax is a syntax sugar of function a -> ...:
Therefore f a b creates the following function:
deriv