简体   繁体   中英

Scope confusion in F#

Let's consider this code:

type TypeA = 
    {
        A : int
    }

type TypeB =
    {
        B : float
    }

module Test =
    let mutable c : TypeA = { A = 0 }

module Test2 =
    let mutable c : TypeB = { B = 0 }

it produces the error:

typecheck error This expression was expected to have type
    'float'    
but here has type
    'int'    

What I do not understand is why there is a collision between the two variables 'c' .

They have different scopes:

type TypeA = 
    {
        A : int
    }

module Test =
    let mutable c : TypeA = { A = 0 }

module Test2 =
    let mutable c : TypeA = { A = 0 }

with

Test.c <- { A = 1 }
Test2.c <- { A = 2 }
Test.c, Test2.c

gives

{ FSI_0009+TypeA: A: 1 } { FSI_0009+TypeA: A: 2 }

Can someone explain why there is this error?

There is no collision between two variables c - they are defined in separate modules. F# just cannot implicitly convet integer literal 0 to float. Use 0.0 or 0. in the second case:

let mutable c : TypeB = { B = 0.0 }

Also, F# type inference is smart enough to infer that the first variable c has type TypeA , and the second variable c has type TypeB (because record labels are different) so you can even remove type annotations here:

module Test =
    let mutable c = { A = 0 } // TypeA inferred

module Test2 =
    let mutable c = { B = 0. } // TypeB inferred

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