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
2
(* - : int = 6 *)
4 + (if 'a' = 'b' then 1 else 2)

Recursive Functions

Recursive functions are defined like this:
let rec f x = ...

Mutually recursive functions can be defined with the and keyword:

1
2
let rec f x1 ... xn = e1
and g y1 ... yn = e2

For example:

1
2
3
4
5
6
7
8
9
(** [even n] is whether [n] is even.
Requires: [n >= 0]. *)
let rec even n =
n = 0 || odd (n - 1)

(** [odd n] is whether [n] is odd.
Requires: [n >= 0]. *)
and odd n =
n <> 0 && even (n - 1);;

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
2
3
4
5
func @@ 2 * 10;;
func @@ 20;;

square (inc 5);;
5 |> inc |> square;;

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
Author

Beijie Liu

Posted on

2024-01-08

Updated on

2024-01-21

Licensed under