Functional Programming

  • supports another form of declarative programming

    • the building block is true function (no side effect)
  • The conceptual model of functional programming is that of a pocket calculator

    • enter an expression, the calculator returns its value
      1
      2
      3
      4
      - 2 + 2;
      val it = 4 : int
      - it;
      val it = 4 : int

Properties

  1. No Variables Allowed

    • there is no variable like those we have in imperative programming
    • we can only declare names and assign values (like constant)
    • we can reuse the same name but cannot mutate the value
  2. Functional Value

    • the last expression (nameless function)

      1
      2
      3
      4
      5
      6
      - fn((x:real),(y:real)) => x*x+y*y;
      val it = fn : real * real -> real

      (* apply the last functional expression to an argument *)
      - fn((x:real),(y:real)) => x*x+y*y (5.0,2.0);
      val it = 29.0 : real
    • name the function

      1
      2
      3
      4
      - val sumsq = fn((x:real),(y:real)) => x*x+y*y;
      val sumsq = fn : real * real -> real
      - sumsq(2,3);
      val it = 1.0 : real
  3. Typing in ML

    • ML is rather picky about types
    • ML is a highly strongly-typed language in that it requires types of operators and operands to be consistent

      • multiplication is either between integers or between reals, but not between an integer and a real
        1
        - 2 * 1.0;  (* ERROR *)
    • Solution:

      1. we can transform the integer to its real couterpart
        1
        2
        - (real 2) * 1.0;
        val it = 2.0 : real
      2. we can also apply a built-in function of type int -> real
        1
        2
        - real(2);
        val it = 2.0 : real
  4. Basic Types

    1. int

      • 0, 1337, ~3
      • Operations: +, -, *, div, mod
    2. real

      • 3.14, 2E4, ~123.4
      • Operations: +, -, *, /
    3. bool

      • true, false
      • Operations: not, and, or, andalso, orelse
      • Noted: andalso and orelse use short-circuit evaluation
    4. string

      • "doge", "is", "awesome"
      • Operations: ^ (conjunction)
        1
        2
        - "doge" ^ "is" ^ "awesome";
        val it = "dogeisawesome" : string
  5. Type Inference

    • ML can infer the types of an expression without the user declaring any time
      1
      2
      3
      4
      5
      6
      - fun sq(x) = x*x;
      val sq = fn : int -> int
      - fun sq(x:real) = x*x;
      val sq = fn : real -> real
      - fun sq x = (x:real)*x;
      val sq = fn : real -> real

Conditional Expression

  • Free standing conditional expression

    1
    2
    3
    - if (floor (323.43*sin(1.0)) mod 2) = 0
    = then "even" else "odd";
    val it = "even" : string
  • Examples:

    • Absolute value abs

      1
      2
      - fun abs x = if x >= 0 then x else ~x;
      val abs = fn : int -> int
    • Check negative negative

      1
      2
      - fun negative x = x < 0;
      val negative = fn : int -> bool

Tuples

  • values can be combined into tuples

    1
    2
    3
    4
    - val origin = (0.0,0.0,0.0);
    val origin = (0.0,0.0,0.0) : real * real * real
    - fun length (x,y,z) = Math.sqrt(x*x + y*y + z*z);
    val length = fn : real * real * real -> real
  • Note: every function in ML is one-argument function

    • it looks like a multi-argument function, but the argument is just a tuple

Selector Functions

  • it is used to explicitly select the components of a tuple
  • underscore _ is the wildcard symbol used in pattern matching (it would ignore the type)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    - fun first (x,_,_) = x;
    val first = fn : 'a * 'b * 'c -> 'a
    - fun second (_,y,_) = y;
    val second = fn : 'a * 'b * 'c -> 'b
    - fun third (_,_,z) = z;
    val third = fn : 'a * 'b * 'c -> 'c

    - first(1,2,3);
    val it = 1 : int

Local Declaration

  • declare a value that have to be local in the function
  • Example: Area of a triangle

    • given that $p$ can simplify a formula
    • since $p$ is only relevant for the computation of $Area$, it is suitable for setting $p$ to be local
  • we can use let for local declaration

    1
    2
    3
    4
    5
    6
    7
    8
    9
    - fun area (a,b,c) = let val p = (a+b+c)/2.0 in 
    = sqrt(p*(p-a)*(p-b)*(p-c))
    = end;
    val area = fn : real * real * real -> real

    - area (1.0,2.0,3.0);
    val it = 0.0 : real
    - area (3.0,4.0,5.0);
    val it = 6.0 : real
  • Local declaration can be used in any expression (not just in function declaration)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    (* Use it in declaraing values *)
    - val (a,b,c) = (3.0,4.0,5.0);
    val a = 3.0 : real
    val b = 4.0 : real
    val c = 5.0 : real
    - let val p = (a+b+c)/2.0 in
    = sqrt(p*(p-a)*(p-b)*(p-c))
    = end;

    val it = 6.0 : real
    (* Cannot access p *)
    p; (* ERROR *)

    (* local function declaration *)
    - fun anniversary age =
    = let fun divides (x,y) = x mod y = 0 in
    = divides(10,age) orelse divides(25,age)
    = end;
    val anniversary = fn : int -> bool

    - anniversary 11;
    val it = false : bool
    - anniversary 5;
    val it = true : bool

User-Defined Types

Enumeration

  • ML supports user-defined types
  • following example is an enumeration type
    1
    2
    3
    4
    - datatype DIRECTION = North | East | South | West;
    datatype DIRECTION = East | North | South | West
    - val dir = East;
    val dir = East : DIRECTION (* dir is DIRECTION type *)

Case Expression

  • case expression is often used naturally in conjunction with enumeration types

    • using | to seperate the different cases

      1
      2
      3
      4
      5
      6
      7
      - val dir = East;
      val dir = East : DIRECTION (* dir is DIRECTION type *)

      - case dir of North => 0
      = | East => 90
      = | South => 180
      = | West => 270;
    • Example:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      - datatype SUIT = Spades | Hearts | Diamonds | Clubs;
      datatype SUIT = Clubs | Diamonds | Hearts | Spades

      - fun gt_suit(_,Spades) = false (* Spades is the largest *)
      = | gt_suit(Spades,_) = true
      = | gt_suit(Clubs,_) = false (* Clubs is the smallest *)
      = | gt_suit(_,Clubs) = true
      = | gt_suit(s1,s2) = s1 = Hearts andalso s2 = Diamonds;
      val gt_suit = fn : SUIT * SUIT -> bool

      - fun gt_card((s1,v1),(s2,v2)) =
      = (v1:int) > v2 orelse
      = (v1 = v2 andalso gt_suit(s1,s2));

      val gt_card = fn : (SUIT * int) * (SUIT * int) -> bool - gt_card((Clubs,12),(Spades,12));
      val it = false : bool
      • Noted: The order in case expression is very important, because it has the checking order

Union

  • a data type that can represent different data types with same memory storage
  • we can define a union using of and |
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    - datatype num = i of int | r of real;
    datatype num = i of int | r of real

    (* Represents int for value a *)
    - val a = i(3);
    val a = i 3 : num

    (* Represents int for value b *)
    - val b = r(4.0);
    val b = r 4.0 : num

Polymorphic

  • we can define polymorphic data types
  • we declare a binary tree using polymorphic data types ('a)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
           (* value, bTree         node     lTree   * root * rTree *)
    - datatype 'a bTree = empty | node of 'a bTree * 'a * 'a bTree;
    datatype 'a bTree = empty | node of 'a bTree * 'a * 'a bTree

    - fun btMem(e,empty) = false (* if empty, false *)
    = | btMem(e,node(left,r,right)) = e = r orelse (* e == r which found *)
    = btMem(e,left) orelse btMem(e,right); (* recursively search for e *)
    val btMem = fn : ''a * ''a bTree -> bool

    - val t = node(node(empty,2,node(empty,4,empty)),
    = 1,
    = node(node(empty,5,empty),3,empty));
    val t = node (node (empty,2,node #),1,node (node #,3,empty)) : int bTree

    - btMem(3,t);
    val it = true : bool
    - btMem(0,t);
    val it = false : bool

List

  • [] denotes empty list
  • Every non-empty tree contains
    1. The first element (head)
    2. The list of remaining elements (tail)

Combination

  • we can combine the head and tail using the cons operator ::, written as H::T

    1
    2
    3
    4
    5
    6
    7
    - 1 :: [];
    val it = [1] : int list
    - 2 :: (1 :: []);
    val it = [2,1] : int list

    (* It is the combination for head and tail only *)
    - [1,2,3] :: 4; (* ERROR *)
  • we can combine two lists using @ operator (append)

    1
    2
    3
    4
    - [1,2,3] @ [4,5,6];
    val it = [1,2,3,4,5,6] : int list
    - it @ [7,8] @ [~9];
    val it = [1,2,3,4,5,6,7,8,~9] : int list

Homogeneous

  • Note: Lists in ML are homogeneous elements of a list must be same type (type sensitivity)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    (* String Type *)
    - ["husky", "shiba"];
    val it = ["husky","shiba"] : string list

    (* [List] Type *)
    - val l = [[4,5,6], [7,8,9]];
    val l = [[4,5,6],[7,8,9]] : int list list
    - [1,2,3] :: l;
    val it = [[1,2,3],[4,5,6],[7,8,9]] : int list list
    - 0 :: l; (* ERROR *)

    (* List combination *)
    - [1,2,3] @ [4.0, 5.0]; (* ERROR *)
    - [1,2,3] @ 2 (* ERROR *)

Operations

  • Build-in function hd() (get the head element) and tl() (get the remaining list)
    1
    2
    3
    4
    5
    6
    7
    - hd([3,4,5,6,7,8,9]);
    val it = 3 : int
    - tl([3,4,5,6,7,8,9]);
    val it = [4,5,6,7,8,9] : int list

    - hd(tl(tl(tl([3,4,5,6,7,8,9]))));
    val it = 6 : int

Pattern Matching

  • using selectors if-then-else to implement summation

    1
    2
    3
    4
    5
    6
    - fun sumList list = if null list then 0    (* if this is empty, then 0 (return 0) *)
    = else hd(list) + sumList(tl(list));
    val sumList = fn : int list -> int

    - sumList([1,2,3,4,5]);
    val it = 15 : int
  • using pattern matching instead of selectors if-then-else to implement summation

    1
    2
    3
    4
    5
    6
    - fun sumList [] = 0
    = | sumList(a::list) = a + sumList list; (* like parsing them into a :: list *)
    val sumList = fn : int list -> int

    - sumList [1,2,3,4];
    val it = 10 : int

Higher-Order Functions

  • functions that take functions as arguments and/or produce functions as values (because function is actually a value)
    • the function double takes f as input (argument) and return another function that always return twice the result of f
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      (* fucntion name: double, f: the argument of double *)
      - fun double f = fn x => 2 * f(x);
      val double = fn : ('a -> int) -> 'a -> int

      (* Delcare the function that be the argument in double *)
      - fun inc x = x + 1;
      val inc = fn : int -> int
      - fun inc2 x = x + 2;
      val inc2 = fn : int -> int

      - double inc 3;
      val it = 8 : int (* (3+1) * 2 *)
      - double inc2 3;
      val it = 10 : int (* (3+2) * 2 *)
      - double inc;
      val it = fn : int -> int

map

  • map function that takes as input a function f and a list [a1, ..., an], and produces the list [f(a1), ..., f(an)] as output
    1
    2
    3
    4
    5
    6
    7
    8
    9
    (* parse the list into x + [xs], then f(x)::map(f, xs) *)
    - fun map(f,[]) = []
    = | map(f,x::xs) = f(x)::map(f,xs);
    val map = fn : ('a -> 'b) * 'a list -> 'b list

    - fun inc x = x + 1;
    val inc = fn : int -> int
    - map(inc,[1,2,3,4]);
    val it = [2,3,4,5] : int list

foldl & foldr

  • It takes as input a function f, an initial value x, and a list [a1, ..., an]
  • foldl produces as output the value f(an, f(an-1, ... , f(a2, f(a1, x))))
  • foldr produces as output the value f(a1, f(a2, ... f(an-1, f(an, x)...)))

    1
    2
    3
    4
    - fun add(x,y) = x + y;     (* It is necessary to use tuple be argument when using foldl *)
    val add = fn : int * int -> int
    - foldl add 1 [2,3,4,5];
    val it = 15 : int
  • Note that the following implementation is wrong as foldl does not expect take 2 arguments for the function f

    1
    2
    3
    - fun add x y = x + y;
    val add = fn : int * int -> int
    - foldl add 1 [2,3,4,5]; (* Error *)
  • We can use the functions in other packages

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    - val L = [1,2,3,4];
    val L = [1,2,3,4] : int list

    - val real_nums = map real L;
    val real_nums = [1.0,2.0,3.0,4.0] : real list

    - val r = foldl Math.pow 1.0 real_nums; (* foldl: pow(4, pow(3, pow(2, pow(1, 1)))) *)
    val r = 262144.0 : real

    - val r = foldr Math.pow 1.0 real_nums; (* foldr: pow(1, pow(2, pow(3, pow(4, 1)))) *)
    val r = 1.0 : real