Slide 1

Slide 1 text

A brief introduction to OCaml Michal Skuza

Slide 2

Slide 2 text

OCaml. Not Ocaml. ❖ Originally known as Objective Caml, ❖ appeared in 1996, 20 yrs ago, France ❖ extends the core Caml language with object-oriented constructs ❖ http://ocaml.org/ ❖ ML-derived, Standard ML

Slide 3

Slide 3 text

F# ❖ Created initially by Microsoft, OCaml dialect, ❖ open source, appeared in 2005, ❖ actually it’s good, ❖ well integrated with .NET ecosystem and Visual Studio, ❖ mostly Windows but other systems support, ❖ http://fsharp.org/

Slide 4

Slide 4 text

Other variants ❖ Js_of_ocaml - compiler of OCaml bytecode to Javascript. ❖ Javascript to the rescue! ❖ supposedly good ❖ http://ocsigen.org/js_of_ocaml/ ❖ OCaml-java ❖ working but still lagging behind ❖ http://www.ocamljava.org/

Slide 5

Slide 5 text

Who uses OCaml? ❖ Mostly OS, academic and financial domains ❖ No killer app yet ❖ Commercial users (according to Wikipedia): ❖ Jane Street Capital, a proprietary trading firm, which adopted OCaml as its preferred language in its early days ❖ Citrix Systems, which uses OCaml in XenServer, a component of one of its products ❖ Facebook ❖ Bloomberg and others.

Slide 6

Slide 6 text

Who uses OCaml? ❖ MirageOS, a unikernel programming framework written in pure OCaml ❖ Hack compiler, a new programming language created by Facebook, an extension of PHP with static typing ❖ 0Install, a multi-platform package manager ❖ Coq, a formal proof management system ❖ https://ocaml.org/learn/companies.html

Slide 7

Slide 7 text

Why OCaml? ❖ expressiveness ❖ a powerful type system ❖ more accessible than Haskell (IMO) ❖ increasing popularity ❖ if you look at hacker news, reddit/r/programming ❖ Github or StackOverflow

Slide 8

Slide 8 text

From Java Perspective ❖ Where are my curly braces? ❖ How do I create new objects? ❖ Actually you can write Java in OCaml if you're determined enough, ❖ but please don’t ༼ つ ◕_◕ ༽つ

Slide 9

Slide 9 text

From Haskell Perspective ❖ Similar but not ❖ impure ❖ because it allows side-effects ❖ not lazy by default

Slide 10

Slide 10 text

OCaml features ❖ multi-paradigm: ❖ functional ❖ imperative & object-oriented ❖ statically and strongly typed, with type inference ❖ user-definable algebraic data types and pattern matching ❖ cross-platform, but works the best in Linux/Unix ❖ open source

Slide 11

Slide 11 text

OCaml features ❖ compiled - native code ❖ or interpreted - byte code ❖ type inference ❖ types are deducted # let n = 6;; val n : int = 6

Slide 12

Slide 12 text

Tooling - editors ❖ No good IDE ❖ Use you favourite editor, be it VIM, Sublime, Atom etc. ❖ Merlin -plugin to VIM, Emacs ❖ type inference ❖ autocompletion ❖ https://github.com/the-lambda-church/merlin

Slide 13

Slide 13 text

Tooling - building ❖ Different types of files ❖ Purpose C Bytecode Native code ❖ Source code *.c *.ml *.ml ❖ Header files1 *.h *.mli *.mli ❖ Object files *.o *.cmo *.cmx2 ❖ Library files *.a *.cma *.cmxa3 ❖ Binary programs prog prog prog.opt4 ❖ bytecode compiler native compiler ❖ ocamlc, ocamlopt ❖ ocamlfind ❖ ocamlbuild - from JaneStreet

Slide 14

Slide 14 text

OCaml standard library ❖ some operations non-tail-recursive ❖ limited - too many things are missing ❖ inconsistent

Slide 15

Slide 15 text

Package manager ❖ OPAM - OCaml Package Manager ❖ http://opam.ocaml.org/ ❖ works like npm

Slide 16

Slide 16 text

REPL - read–eval–print loop ❖ Standard REPL ❖ ocaml ❖ utop - a universal toplevel for OCaml ❖ can be installed via spam ❖ multiline edition, history, real-time and context sensitive completion, colours

Slide 17

Slide 17 text

Standard REPL vs utop

Slide 18

Slide 18 text

OCaml standard library ❖ Alternatives ❖ Core - JaneStreet’s library - not compatible with stlib ❖ https://ocaml.janestreet.com/ocaml-core/ 111.28.00/doc/core/ ❖ Batteries - OS ❖ http://batteries.forge.ocamlcore.org/

Slide 19

Slide 19 text

What to read ?

Slide 20

Slide 20 text

Real World OCaml ❖ Real World OCaml ❖ https://realworldocaml.org/ ❖ Fully available as HTML online. ❖ Free of charge. ❖ An extensive section on the runtime ❖ A whole section about tooling ❖ Focused mostly around JaneStreet core library

Slide 21

Slide 21 text

What to read ? ❖ OCaml in browser ❖ https://try.ocamlpro.com/ ❖ Official documentation ❖ http://ocaml.org/

Slide 22

Slide 22 text

What's missing ❖ ocamldebug ❖ debugging is pretty awkward ❖ printing debug info to the rescue ¯\_(ツ)_/¯ ❖ profiling ❖ ocamlprof ❖ gprof ❖ buggy

Slide 23

Slide 23 text

Where’s code ?

Slide 24

Slide 24 text

REPL ❖ (* Comment*) ❖ ;; to execute code ❖ Show all packages installed ❖ #list;; ❖ Examples mostly from Learn X in Y minutes - OCaml ❖ https://learnxinyminutes.com/docs/ocaml/

Slide 25

Slide 25 text

Types ❖ (* Load a package *) ❖ #require "num";; ❖ Num.num_of_int 42;; ❖ 1;; ❖ 3.14;; ❖ 'c';; ❖ "chars";; ❖ true;; false;; ❖ ();;

Slide 26

Slide 26 text

Arithmetic operations ❖ 12 + 3 ;; (* Integer addition. *) ❖ 12.0 +. 3.0 ;; (* Floating point addition. *) ❖ 12 / 3 ;; (* Integer division. *) ❖ sqrt 5.0;; ❖ Arithmetic operators are not overloaded for float and double ❖ 12.0 /. 3.0 ;; (* Floating point division. *) ❖ 5 mod 2 ;; (* Remainder. *)

Slide 27

Slide 27 text

Boolean operations ❖ 1 = 1;; (* Structural equality *) ❖ 1 <> 2;; ❖ physical equality (same pointer in memory), important for mutable states ❖ 1 == 1;; ❖ less-than, greater-than, and, or ❖ 1 < 3 || 4 <= 2;; ❖ 1 >= 3 && 4 <= 2 || not true;;

Slide 28

Slide 28 text

Strings and characters ❖ let my_str = "Hello world" ;; ❖ let my_char = 'a' ;; ❖ let bad_str = 'syntax error' ;; (* Syntax error. *) ❖ let some_str = "hello" ^ "world" ;; ❖ Printf.printf "%d %s" 99 "bottles of beer" ;; ❖ print_string "hello world\n" ;; ❖ print_endline "hello world" ;; ❖ let line = read_line () ;;

Slide 29

Slide 29 text

Function application ❖ No parenthesis around or commas between arguments needed ❖ String.sub "Hello" 1 2;; (* Substring *) ❖ int_of_float 3.0;; (* No need for parenthesis *) ❖ float_of_int 4;;

Slide 30

Slide 30 text

Variables ❖ Variable and function declarations use "let" keyword. ❖ Immutable ❖ let x = 10 ;; ❖ Expressions allowed ❖ let y = x * 2;;

Slide 31

Slide 31 text

Let-bindings - naming values and expressions ❖ Two different let variants: ❖ local definitions ❖ global definitions ❖ let _ = int_of_float 3.14 ❖ _ - we don't care about return value

Slide 32

Slide 32 text

Chaining let expressions ❖ let x = 4 in ❖ let y = 3 * 4 in ❖ 4 - y - x * 2;; ❖ let _ = 10 + (let n = 2 in n * n)

Slide 33

Slide 33 text

Functions ❖ let my_lambda = fun x -> x * x ;; ❖ let sqr = fun x -> x * x;; ❖ Special syntax ❖ let sqr x = x * x;; ❖ let mul x y = x * y;;

Slide 34

Slide 34 text

Recursive definitions ❖ keyword rec mandatory ❖ let rec fac n = ❖ if n == 0 then 1 else n * fac (n - 1);; ❖ or ❖ let rec factorial n = ❖ if n = 0 then 1 ❖ else n * factorial (n-1);;

Slide 35

Slide 35 text

Recursive function definition let rec is_even = function | 0 -> true | n -> is_odd (n-1) and is_odd = function | 0 -> false | n -> is_even (n-1);;

Slide 36

Slide 36 text

Function ctd. ❖ Functions in OCaml take and return exactly one argument! ❖ Multiple arguments ❖ tuples ❖ currying

Slide 37

Slide 37 text

OCaml is functional ❖ Functions are first class ❖ Functions can be used as arguments ❖ let inc = fun x -> x + 1;; ❖ let appl2 f x = f (f x);; ❖ let _ = appl2 inc 3;;

Slide 38

Slide 38 text

Type inference ❖ OCaml is strongly typed ❖ let add x y = x + y;; ❖ val add : int -> int -> int = ❖ We can also specify types ❖ let add (x : int) (y : int) :int = x + y;;

Slide 39

Slide 39 text

Parametric polymorpism ❖ List.length;; ❖ has the type 'a list -> int = ❖ let make_list x = [x];; ❖ val make_list : 'a -> 'a list =

Slide 40

Slide 40 text

Tuples ❖ int * string, int * int * float ❖ Can be heterogeneous ❖ Parenthesis are optional ❖ let _ = 1, „five”;; ❖ let _ = (1, 4, 5.0);; ❖ let x, y = (10, 20);;

Slide 41

Slide 41 text

Arrays ❖ (* Arrays are enclosed in [| |] *) ❖ let my_array = [| 1; 2; 3 |] ;; ❖ (* You can access array items like this: *) ❖ my_array.(0) ;;

Slide 42

Slide 42 text

Lists ❖ int list, string list ❖ Immutable ❖ Homogeneous (all elements must have the same type) ❖ let xs = [1; 3; 23; 5; 77] ❖ let _ = [1, 2, 3] ❖ let _ = 132 :: xs (* Prepend elem onto a list "cons" *) ❖ let _ = [13; 54; 59] @ xs ❖ let _ = List.length xs

Slide 43

Slide 43 text

Map and folds ❖ let _ = List.map (fun x -> x * x) [9; 4; 3; 2] ❖ let _ = List.filter (fun x -> x mod 2 = 0) [9; 4; 3; 2] ❖ (* Reductions/Fold *) ❖ let _ = List.fold_left (fun x y -> x + y) 0 [9; 4; 3; 2] ❖ let _ = List.fold_left (+) 0 [9; 4; 3; 2] ❖ let _ = List.fold_left (*) 0 [9; 4; 3; 2] (* Problem !*)

Slide 44

Slide 44 text

Pattern matching ❖ like enums on steroids ❖ but much more useful ❖ let is_zero x = ❖ match x with ❖ | 0 -> true ❖ | _ -> false;;

Slide 45

Slide 45 text

Pattern matching ❖ let is_one x = ❖ match x with ❖ | 1 -> true ❖ | _ -> false;;

Slide 46

Slide 46 text

❖ (* Matching predicates, aka "guarded pattern matching". *) ❖ let abs x = ❖ match x with ❖ | x when x < 0 -> -x ❖ | _ -> x;; ❖ abs 5 ;; (* 5 *) ❖ abs (-5) (* 5 again *)

Slide 47

Slide 47 text

Data types (Sum types, Variant types) ❖ type week_day = Mon | Tue | Wed | Thu | Fri;; ❖ let best_week_day = Fri;; ❖ Types in constructor ❖ type animal = Dog of string | Cat of string ;; ❖ let garfield = Cat "Garfield";;

Slide 48

Slide 48 text

Pattern Matching with Data types ❖ let say x = ❖ match x with ❖ | Dog x -> x ^ " says woof" ❖ | Cat x -> x ^ " says meow";;

Slide 49

Slide 49 text

The Option type ❖ type 'a option = None | Some of 'a ❖ Similar to Haskell ❖ let div x y = ❖ if y == 0 then None ❖ else Some (x / y);;

Slide 50

Slide 50 text

Records ❖ type book = {author : string; title : string; pages : int};; ❖ let ps = {author="Peter F. Hamilton"; title="Pandoras Star"; pages=1144};; ❖ Records are immutable by default ❖ let title b = b.title;;

Slide 51

Slide 51 text

Imperative Programming ❖ Mutable state! ❖ Arrays are mutable ❖ Ref cells - mutable variable ❖ type 'a ref = { mutable contents : 'a };; ❖ let x = ref 1;; ❖ !x;; ❖ x := !x + 1;;

Slide 52

Slide 52 text

Imperative Programming ❖ for and while loops ❖ for i = 0 to 3 do printf "i = %d\n" i done;; ❖ for i = 3 downto 0 do printf "i = %d\n" i done;;

Slide 53

Slide 53 text

Laziness ❖ OCaml is not lazy by default ❖ let v = lazy (print_string "performing lazy computation \n"; sqrt 16.);; ❖ Lazy.force v;;

Slide 54

Slide 54 text

Modules ❖ The key parts of the module system in OCaml are: ❖ - Structures (~ value) ❖ - Signatures (~ type) ❖ - Functors (~ functions)

Slide 55

Slide 55 text

Modules ❖ Structures - provide a way for grouping together related declarations like data types and functions the operate on them ❖ Signatures - are the interfaces for structures ❖ Functors - functions from structures to structures

Slide 56

Slide 56 text

Not covered in this presentation ❖ OCaml module system in detail ❖ Objects ❖ Classes ❖ Concurrency ❖ Libs

Slide 57

Slide 57 text

That’s the end ❖ Try OCaml online ❖ https://try.ocamlpro.com/ ❖ ok ? then grab the book - Real World OCaml ❖ https://realworldocaml.org/ ❖ happy coding :)

Slide 58

Slide 58 text

Questions ?