1
votes
val x = 1

fun f y =
  let
    val x = y+1
  in
    fn z => x + y + z
  end

val x = 3
val g = f 4
val y = 5
val z = g 6

I'm currently trying to understand function closures and lexical scope in the above code segment. In this example, why is g a function instead of a val binding? To my understanding, g is calling f(4) and should be bound to the return value. However, the typechecker says g is of type fn : int -> int. I'm confused as to why that is.

1
A function is just a special type of value. f is a higher-order function whose return value is itself a function, so of course f 4 is a function. What else do you expect it to be? What is the type of f? - John Coleman
Right! I overlooked the return type of f. For some reason, I thought it returned an int. I now see that it returns a function. - yesar

1 Answers

0
votes

f returns a function, so the value bound to g has a function type.