Introduction to functional programming using Ocaml

Embed Size (px)

DESCRIPTION

Key Functional Programming concepts illustrated using Ocaml

Text of Introduction to functional programming using Ocaml

  • 1. Introduction to Functional Programming with Ocaml Pramode C.E http://pramode.net January 30, 2014
  • 2. Workshop Plan Here is what we will do: Learn some Ocaml syntax and write simple Ocaml programs Learn important concepts like: closures, higher order functions, purity, lazy vs strict evaluation, currying, tail calls/TCO, immutability, persistent data structures, type inference etc! Understand the essence of the "Functional Programming" paradigm through Ocaml Not beginner-level stu - but I will try to keep things as simple as possible! Pramode C.E Introduction to Functional Programming with Ocaml
  • 3. Ocaml - some background info Written in 1996 by Xavier Leroy and other researchers at INRIA, France A member of the ML family http://en.wikipedia.org/wiki/ML_(programming_language) Supports Functional, Imperative and Object oriented programming A powerful static type system with type inference Major inuence behind Microsoft F# Recent developments: the Core standard library (by Jane Street) and realworldocaml.org Pramode C.E Introduction to Functional Programming with Ocaml
  • 4. Pramode C.E Introduction to Functional Programming with Ocaml
  • 5. Where is it being used? List of companies: http://ocaml.org/learn/companies.html Facebook - pf, a tool for analysing PHP source Citrix - Uses Ocaml in XenServer, a virtualization system Jane Street - develops trading systems in Ocaml Bloomberg - uses Ocaml for developing nancial derivatives risk management applications Pramode C.E Introduction to Functional Programming with Ocaml
  • 6. The Ocaml REPL Invoke the REPL with the "utop" command at the shell prompt: utop # print_string "hellon";; hello - : unit = () utop # 2 * 3;; - : int = 6 utop # let x = 10;; val x : int = 10 utop # x * 2;; - : int = 20 utop # let y = 5 in y * 8;; - : int = 40 utop # Question: what is the dierence between "let" and "let ... in"? Pramode C.E Introduction to Functional Programming with Ocaml
  • 7. Function Denition let add a b = a + b let m = add 10 20 We dene add to be a function which accepts two parameters of type int and returns a value of type int. Similarly, m is dened as a variable of type int. But wait ... we haven't actually dened all these types! Pramode C.E Introduction to Functional Programming with Ocaml
  • 8. Type Inference We have NOT specied the return type of the function or the type of the variable m. Ocaml infers that (the technical term is HindleyMilner type inference) This is the type which utop shows us: val add : int -> int -> int Read this as: function takes two int's as arguments and returns an int. Pramode C.E Introduction to Functional Programming with Ocaml
  • 9. Static vs Dynamic typing #Python - dynamic typing def foo(x): return x/2 /* C - static typing with NO type inference */ int foo(int x) { return x / 2; } (* ML - static typing with type inference *) let foo x = x / 2 Pramode C.E Introduction to Functional Programming with Ocaml
  • 10. Expression Oriented Programming let i = 0 let p = if (i > 0) then -1 else -2 let q = if (true) then "hello" else "world" Unlike languages like C/Java, almost everything in Ocaml is an expression, ie, something which computes a value! Rather than programming with statements, we program with expressions. Pramode C.E Introduction to Functional Programming with Ocaml
  • 11. Recursion (* compute sum of first n numbers *) let rec sum n = if (n = 0) then 0 else n + sum (n - 1) let r = sum 10 Try calling the function "sum" with a large number (say 1000000) as parameter! You get a stack overow! Pramode C.E Introduction to Functional Programming with Ocaml
  • 12. Tail Calls and TCO (* compute sum of first n numbers *) let rec sum n acc = if (n = 0) then acc else sum (n - 1) (acc + n) let r = sum 10 0 This is a "tail-recursive" version of the previous function - the Ocaml compiler converts the tail call to a loop, thereby avoiding stack overow! Pramode C.E Introduction to Functional Programming with Ocaml
  • 13. Tail Calls and TCO (sum 4) (4 + sum 3) (4 + (3 + sum 2)) (4 + (3 + (2 + sum 1))) (4 + (3 + (2 + (1 + sum 0)))) (4 + (3 + (2 + (1 + 0)))) (4 + (3 + (2 + 1))) (4 + (3 + 3)) (4 + 6) (10) -----------------------------(sum 4 0) (sum 3 4) (sum 2 7) (sum 1 9) (sum 0 10) (10) Pramode C.E Introduction to Functional Programming with Ocaml
  • 14. Parametric polymorphism let foo x = x Our function "foo" is the identity function; it takes in a value and returns the same! What is the inferred type of this function? More examples: let foo x y = x let foo2 x y = if true then x else y let foo3 x y = if x then y else y let foo4 x y = if x then y else x Pramode C.E Introduction to Functional Programming with Ocaml
  • 15. Higher order functions let double x = 2*x let triple x = 3*x let apply f x = f x let p = apply double 10 let q = apply triple 10 What is type of "apply"? Pramode C.E Introduction to Functional Programming with Ocaml
  • 16. Summation once again! let sqr x = x * x let cube x = x * x * x let rec sumSimple a b = if a = b then a else a + sumSimple (a + 1) b let rec sumSquares a b = if a = b then (sqr a) else (sqr a) + sumSquares (a + 1) b let rec sumCubes a b = if a = b then (cube a) else (cube a) + sumCubes (a + 1) b Pramode C.E Introduction to Functional Programming with Ocaml
  • 17. Summation - a more elegant method let identity x = x let sqr x = x * x let cube x = x * x * x let rec sum f a b = if a = b then (f a) else (f a) + sum f (a + 1) b let p = sum identity 0 4 let q = sum sqr 0 4 let r = sum cube 0 4 Pramode C.E Introduction to Functional Programming with Ocaml
  • 18. Anonymous functions let apply f x = f x let p = apply (fun x -> 2*x) 10 We can create "anonymous" functions on-the-y! fun x -> 2*x is a function which takes an "x" and returns 2*x. Pramode C.E Introduction to Functional Programming with Ocaml
  • 19. Methods on collections: Map/Filter/Reduce open Core.Std let a = [1;2;3;4] let p = List.map a (fun x -> x * x) let q = List.filter a (fun x -> (x mod 2) = 0) let r = List.reduce a (fun x y -> x + y) Map applies a function on all elements of a sequence. Filter selects a set of values from a sequence based on the boolean value returned by a function passed as its parameter - both functions return a new sequence. Reduce combines the elements of a sequence into a single element. Pramode C.E Introduction to Functional Programming with Ocaml
  • 20. More methods on collections open Core.Std let even x = (x mod 2) = 0 let a = [1;2;3;4;5;6;7] let b = [2;4;6;5;10;11;13;12] let let let let c d e f = = = = List.for_all a even List.exists a even List.take_while a even List.partition_tf a even Pramode C.E Introduction to Functional Programming with Ocaml
  • 21. Nested functions / functions returning functions (* foo returns sqr *) let foo () = let sqr x = x * x in sqr let f = foo () let g = f 10 Pramode C.E Introduction to Functional Programming with Ocaml
  • 22. Lexical Closure let foo1 x = let foo2 y = x + y in foo2 let f = foo1 10 let r = f 20 Pramode C.E Introduction to Functional Programming with Ocaml
  • 23. Lexical Closure The function "foo1" returns a "closure". A "closure" is a function which carries with it references to the environment in which it was dened. When we call f(20), the "foo2" function gets executed with the environment it had when it was dened - in this environment, the value of "x" is 10. Pramode C.E Introduction to Functional Programming with Ocaml
  • 24. Simple closure examples let sqr x = x * x let cube x = x * x * x let compose f g = fun x -> f (g x) let f = compose sqr cube let m = f 2 Pramode C.E Introduction to Functional Programming with Ocaml
  • 25. Simple closure examples open Core.Std let remove_low_scores xs threshold = List.filter xs (fun score -> score

Recommended

View more >