0
votes

I'm taking the Programming Languages course on Coursera and I'm having trouble understanding the following examples regarding static and dynamic scopes.

Consider the code sample and the quiz associated with it

fun f g = let val x = 9 in g() end
val x = 7
fun h() = x+1
val y = f h

What value does y have under lexical scope (like in ML) and under dynamic scope (unlike in ML)?

The answer to the question is "8 under lexical scope and 10 under dynamic scope" and the reason given is "Under dynamic scope, the body of function h would end up "seeing" the local binding of x to 9 and if we removed this local binding (since it appears to have no purpose), then dynamic scope would lead to an undefined variable."

Consider the following code snippet and the explanation given as to why dynamic scope wouldn't work for this case.

fun f y =
 let val q = y+1 
 in fn z => q + y + z
 end
val g = f 4
val y = 5
val z = g 6

Under dynamic scope, now the call to g 6 will make no sense: we will try to look up q, but there is no q in the environment at the call-site.

In the first example, the local val binding in the let expression "val x = 9" was considered while in the second example "val q = y+1" is not considered. What is the reason behind this?

1
This doesn't sound like dynamic scope as it usually works. - molbdnilo
@molbdnilo , are you referring to the first example? - srib

1 Answers

1
votes

In the first example val x = 9 is in scope when g() is called, so g can see it under dynamic scoping rules.

In the second example, val q = y+1 is only in scope inside f. It is not in scope when g is called on the line val z = g 6.