If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Saturday, October 19, 2013

A few examples of how lexical scope works (ML)

A function body is evaluated in the environment where the function was defined (created).
val x = 1
fun f y =
let
val x = y + 1
in
fn z => x + y + z (* will return 2y + 1 + z *)
end
val x = 3 (* irrelevant *)
val g = f 4 (* return a function that ads 9 to its argument *)
val y = 5 (* irrelevant *)
val z = g 6 (* get 15 *)
(* output of program
- use "lexical1.sml";
[opening lexical1.sml]
val x = <hidden-value> : int
val f = fn : int -> int -> int
val x = 3 : int
val g = fn : int -> int
val y = 5 : int
val z = 15 : int
val it = () : unit
*)
view raw gistfile1.sml hosted with ❤ by GitHub
fun f g =
let
val x = 3 (* irrelevant *)
in
g 2
end
val x = 4
fun h y = x + y (* add 4 to its argument *)
val z = f h (* get 6 *)
(* output of program
- use "lexical2.sml";
[opening lexical2.sml]
val f = fn : (int -> 'a) -> 'a
val x = 4 : int
val h = fn : int -> int
val z = 6 : int
val it = () : unit
*)
view raw gistfile1.sml hosted with ❤ by GitHub

No comments:

Post a Comment