val y=2;
fun f(x) = x*y;
fun g(h) = let val y=5 in 3+h(y) end;
let val y=3 in g(f) end;
I’m looking for a line by line explanation. I’m new to ML and trying to decipher some online code. Also, a description of the “let/in” commands would be very helpful.
I’m more familiar with ocaml but it all looks the same to me.
The first two lines bind variables
yandf.yto an integer2andfto a function which takes an integerxand multiplies it by what’s bound toy,2. So you can think of the functionftakes some integer and multiplies it by2. (f(x) = x*2)The next line defines a function
gwhich takes someh(which turns out to be a function which takes an integer and returns an integer) and does the following:5to a temporary variabley.let/in/endsyntax as a way to declare a temporary variable which could be used in the expression followingin.endjust ends the expression. (this is in contrast to ocaml whereendis omitted)3plus the functionhapplying the argumenty, or5.At a high level, the function
gtakes some function, applies5to that function and adds3to the result. (g(h) = 3+h(5))At this point, three variables are bound in the environment:
y = 2,f = functionandg = function.Now
3is bound to a temporary variableyand calls functiongwith the functionfas the argument. You need to remember that when a function is defined, it keeps it’s environment along with it so the temporary binding ofyhere has no affect on the functionsgandf. Their behavior does not change.g(g(h) = 3+h(5)), is called with argumentf(f(x) = x*2). Performing the substitutions for parameterh,gbecomes3+((5)*2)which evaluates to13.I hope this is clear to you.