简体   繁体   中英

Dynamic scope, F#

I'm trying to figure out what this function will evaluate to in F# in a dynamic scope

let y = 3 in 
    let f g = g 2 + g y in   
        let y = f (fun x -> x +  4) in
            f (fun x -> x + y)

I know that in static scope the answer is 31, but I´m having a problem figuring out what it is in dynamic scope

I assume that this is an academic question, so I will not give a full answer, but try to provide some hints for you to solve this on your own. This is also not really an F# question, because F# uses static scope.

The idea with dynamic scope is essentially that variables will refer to values that were assigned to a given name last during the execution of the program.

In your example, the key thing are the references to the variable y . In Static scope, the reference on line 2 refers to declaration on line 1 and the reference on line 4 refers to definition on line 3:

01: let y = 3 in 
02: let f g = g 2 + g y (* ref to line 1 *) in   
03: let y = f (fun x -> x + 4) in
04: f (fun x -> x + y (* ref to line 3 *) )

With dynamic scope, the references to y will point to whatever was the last definition of y encountered in the program execution. When running f on line 3, the reference on line 2 will refer to the value defined on line 1. When running the code in line 4, all references to y will refer to value defined on line 3.

To make this easier to explain, I'll rewrite this with two versions of f , f1 and f2 that refer to different variables:

01:  let y = 3 in 
02a: let f1 g = g 2 + g y (* ref to line 1 *) in   
02b: let f2 g = g 2 + g y (* ref to line 3 *) in   
03:  let y = fa (* last y in scope defined on line 1 *) (fun x -> x + 4) in
04:  fb (* last in scope defined on line 3 *) (fun x -> x + y (* ref to line 3 *) )

With this, you should be able to figure out what the result will be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM