Search code examples
smlsmlnj

Confusing SML statement


I have this statement:

let val x = 
    let val x = 5
    in(fn y =>(y,x+y))
    end
     in
     let val y=3 and z=10
     in x z 
     end 
     end;

The output is :

(10,15)

I've been trying to track how this answer was produced but am getting confused. Is there a better way to write this that would help me understand what variables are being used where? Thank you!


Solution

  • First, some alpha-conversion:

    let val fnPairOfInputAndInputPlus5 = 
        let val five = 5
         in ( fn input => ( input, five + input ) )
        end
     in let val ignored = 3 and input = 10
         in fnPairOfInputAndInputPlus5 input 
        end 
    end;
    

    This code is demonstrating that when you declare a function value, unbound values in the declaring scope, such as the value five, are "enclosed" by the declaration (hence the term "closures"). Thus the function always returns a pair consisting of its input and its input plus five.