Closures and Evaluation of Function Application, Order of Evaluation in OCaml
Functions with more than one argument
# let add_three x + y + z = x + y + z;;
val add_three : int -> int -> int -> int = <fun>
# let t = add_three 6 3 2;;
val t : int = 11
# let add_three =
fun x -> (fun y -> (fun z -> x + y + z));;
val add_three : int -> int -> int -> int = <fun> - What is the value of add_three?
- \(\textcolor{blue}{\text{Let $\rho_{add\_three}$ be the environment before the declaration}}\)
- Remeber: \(\begin{align*} &\textcolor{blue}{\text{let add three = }} \\ &\qquad\textcolor{blue}{\text{fun x $\rightarrow$ (fun y $\rightarrow$ (fun z $\rightarrow$ x + y + z))}} \\ &\text{Value:} \textcolor{blue}{< x \rightarrow \text{ fun y $\rightarrow$ (fun z $\rightarrow$ x + y + z)}, \rho_{add\_three >}} \end{align*}\)
let h = add_three 5 4;;
val h : int -> int = <fun>
h 3;;
- : int = 12
h 7;;
- : int = 16Partial application also called sectioning
Functions as arguments# let thrice f x = f(f(f x));;
val thrice : ('a -> 'a) -> ('a -> 'a) = <fun>
# let g = thrice plus_two;;
val g : int -> int = <fun>
# g 4;;
- : int = 10
# thrice (fun s -> "Hi!" ^ s) "Good-bye!";;
- : string = "Hi! Hi! Hi! Good-bye!"