Ocaml

An introduction to Ocaml. Learn function programming syntax, and build parser and lexer.


  • Ocaml checks data types at compile time
  • Uses static and latent typing
  • To minimize side effects, variables in Ocaml are immutable
  • Since variables are immutable, they cannot be overwritten
    • i.e once a variable is assigned a value, it cannot be changed
let x = 5;;
print_int x;; (* Output: 5 *)
 
x = 10;; 
(* -> Error: This expression has type int but an expression was expected of type unit *)

Tools

opam package manager for OCaml

opam install <package-name>

The REPL (Read-Eval-Print Loop) is an interactive programming environment great for testing small pieces of code or learning OCaml.

ocaml

utop is a more advanced, user-friendly version of the OCaml REPL. Features like syntax highlighting, auto-completion, and better error messages.

opam install utop
utop

dune builds and compiles Ocaml code. Needs to define a dune file in the root project, specifying how the code should be built.

dune build

Run project

dune utp src

Declarative vs Imperative

Imperative

  • Programmer specifies the exact sequence of steps that the program should take to achieve its goal
  • Describes control flow
  • Such as for loops
# imperative.rb
results = []
arr.each{|item|
	remainder = item % 2 
	if remainder == 0
		results.push(0)
	end
}
results

Declarative

  • Programmer specifies what the program should achieve, rather than how to achieve it.
  • Such as Array methods in JS
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(n => n * 2);

Side Effects

Side effects are changes that occur as a result of executing a code block. These changes may include modifications to variables or objects outside of the function scope, changes to the state of the program, or even external systems such as files or networks.

Side effects can cause several problems in programming such as

  • Debugging issues
  • Predictability
  • Readability and maintainability
  • Testing
Example:

f(x)+f(x)+f(x)=3∗f(x)f(x) + f(x) + f(x) = 3 * f (x)

  • However, if we run the code above, then
  • f(x)+f(x)+f(x)=1+2+3f(x) + f(x) + f(x) = 1 + 2 + 3 and 3∗f(x)=3∗13 * f(x) = 3 * 1.
  • This unpredictability is called a side effect
  • The true definition of a side effect is when non local variables get modified