Shadowing and Nested function

前端 未结 2 2075
谎友^
谎友^ 2020-11-27 22:40

I want to understand how the mechanism of Shadowing and Nested function work. For example:

let func y =
    let dup y = y + y
    let z = dup y
    let dup y         


        
2条回答
  •  攒了一身酷
    2020-11-27 22:49

    Your code is equivalent to the following, where I've simply numbered instances of your names to help you visualize how shadowing is occurring.

    let func y0 = 
      let dup0 y1 = y1 + y1
      let z0 = dup0 y0
      let dup1 y2 = 
        let dup2 z1 = 
          let y3 = y2 * z1 
          y3
        let z2 = y2 
        y2 
      dup1 z0 + z0
    

    This can be further simplified, of course. Since dup2 and z2 are never used, dup1 is equivalent to let dup1 y2 = y2, and the whole function is equivalent to

    let func y0 =
      let dup0 y1 = y1 + y1
      let z0 = dup0 y0
      dup1 z0 + z0
    

    Which is equivalent to

    let func y0 =
      let z0 = y0 + y0
      z0 + z0
    

    by substitution. This is the same as

    let func y0 = 4 * y0
    

    Does this help?

提交回复
热议问题