Search code examples
functionpattern-matchinganonymous-functionsmlsmlnj

Why does this Standard ML expression equal 11?


Can anyone explain to me and help me understand why the following expression equals 11 in standard ML? Any help is greatly appreciated.

(fn f => (fn g => f(g 2))) (fn n => n+3) (fn n => n*4)

Solution

  • You can evaluate the expression:

    (fn f => (fn g => f(g 2))) (fn n => n+3) (fn n => n*4)
    

    Here, replace f with (fn n => n+3) so it becomes

    (fn g => (fn n => n+3)(g 2)) (fn n => n*4)
    

    Similarly, replace g with (fn n => n*4) so it becomes

    (fn n => n+3)((fn n => n*4) 2)
    

    Similarly, replace either the first n with ((fn n => n*4) 2) or the second n with 2.