Upgrade to Pro — share decks privately, control downloads, hide ads and more …

A brief introduction to OCaml

A brief introduction to OCaml

#functional #programming #ocaml

Michal Skuza

April 07, 2016
Tweet

More Decks by Michal Skuza

Other Decks in Technology

Transcript

  1. 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
  2. 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/
  3. 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/
  4. 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.
  5. 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
  6. 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
  7. 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 ༼ つ ◕_◕ ༽つ
  8. From Haskell Perspective ❖ Similar but not ❖ impure ❖

    because it allows side-effects ❖ not lazy by default
  9. 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
  10. OCaml features ❖ compiled - native code ❖ or interpreted

    - byte code ❖ type inference ❖ types are deducted # let n = 6;; val n : int = 6
  11. 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
  12. 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
  13. 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
  14. 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/
  15. 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
  16. What to read ? ❖ OCaml in browser ❖ https://try.ocamlpro.com/

    ❖ Official documentation ❖ http://ocaml.org/
  17. What's missing ❖ ocamldebug ❖ debugging is pretty awkward ❖

    printing debug info to the rescue ¯\_(ツ)_/¯ ❖ profiling ❖ ocamlprof ❖ gprof ❖ buggy
  18. REPL ❖ (* Comment*) ❖ ;; to execute code ❖

    Show all packages installed ❖ #list;; ❖ Examples mostly from Learn X in Y minutes - OCaml ❖ https://learnxinyminutes.com/docs/ocaml/
  19. Types ❖ (* Load a package *) ❖ #require "num";;

    ❖ Num.num_of_int 42;; ❖ 1;; ❖ 3.14;; ❖ 'c';; ❖ "chars";; ❖ true;; false;; ❖ ();;
  20. 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. *)
  21. 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;;
  22. 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 () ;;
  23. 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;;
  24. Variables ❖ Variable and function declarations use "let" keyword. ❖

    Immutable ❖ let x = 10 ;; ❖ Expressions allowed ❖ let y = x * 2;;
  25. 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
  26. Chaining let expressions ❖ let x = 4 in ❖

    let y = 3 * 4 in ❖ 4 - y - x * 2;; ❖ let _ = 10 + (let n = 2 in n * n)
  27. 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;;
  28. 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);;
  29. 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);;
  30. Function ctd. ❖ Functions in OCaml take and return exactly

    one argument! ❖ Multiple arguments ❖ tuples ❖ currying
  31. 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;;
  32. Type inference ❖ OCaml is strongly typed ❖ let add

    x y = x + y;; ❖ val add : int -> int -> int = <fun> ❖ We can also specify types ❖ let add (x : int) (y : int) :int = x + y;;
  33. Parametric polymorpism ❖ List.length;; ❖ has the type 'a list

    -> int = <fun> ❖ let make_list x = [x];; ❖ val make_list : 'a -> 'a list = <fun>
  34. 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);;
  35. Arrays ❖ (* Arrays are enclosed in [| |] *)

    ❖ let my_array = [| 1; 2; 3 |] ;; ❖ (* You can access array items like this: *) ❖ my_array.(0) ;;
  36. 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
  37. 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 !*)
  38. Pattern matching ❖ like enums on steroids ❖ but much

    more useful ❖ let is_zero x = ❖ match x with ❖ | 0 -> true ❖ | _ -> false;;
  39. Pattern matching ❖ let is_one x = ❖ match x

    with ❖ | 1 -> true ❖ | _ -> false;;
  40. ❖ (* 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 *)
  41. 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";;
  42. Pattern Matching with Data types ❖ let say x =

    ❖ match x with ❖ | Dog x -> x ^ " says woof" ❖ | Cat x -> x ^ " says meow";;
  43. 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);;
  44. 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;;
  45. 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;;
  46. 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;;
  47. Laziness ❖ OCaml is not lazy by default ❖ let

    v = lazy (print_string "performing lazy computation \n"; sqrt 16.);; ❖ Lazy.force v;;
  48. Modules ❖ The key parts of the module system in

    OCaml are: ❖ - Structures (~ value) ❖ - Signatures (~ type) ❖ - Functors (~ functions)
  49. 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
  50. Not covered in this presentation ❖ OCaml module system in

    detail ❖ Objects ❖ Classes ❖ Concurrency ❖ Libs
  51. That’s the end ❖ Try OCaml online ❖ https://try.ocamlpro.com/ ❖

    ok ? then grab the book - Real World OCaml ❖ https://realworldocaml.org/ ❖ happy coding :)