为什么多次调用这个F#惰性表达式?

时间:2018-01-06 17:06:50

标签: f#

在下面的代码中,我预计我的惰性计算中的表达式只会被调用一次。 (我预计这些城市只会加载一次。)

type MyDataClass() = 
    static member Cities = lazy ( 
        printfn "Loading cities..."
        [ "Raleigh"; "Durham"; "Chapel Hill" ]
     )

[<EntryPoint>]
let main _ =
    printfn "%A" MyDataClass.Cities.Value
    printfn "%A" MyDataClass.Cities.Value
    0 

事实上,以下输出显示城市已加载两次。

lazy-test/> dotnet run
Loading cities...
["Raleigh"; "Durham"; "Chapel Hill"]
Loading cities...
["Raleigh"; "Durham"; "Chapel Hill"]

为什么我的延迟计算中的表达式被多次调用?

1 个答案:

答案 0 :(得分:2)

lazy表达式被多次计算,因为每次访问时,类的静态属性都会返回一个新的延迟实例。也就是说,延迟计算被编译成get_Cities()方法。每次获得该属性的值时,都会返回一个新的Lazy<string list>实例。每个新返回的Lazy<string list>尚未进行评估。

以下是错误代码的一些替代方法:

// use an auto-implemented property
type MyDataClass() = 
    static member val Cities = lazy ( 
        printfn "Loading cities..."
        [ "Raleigh"; "Durham"; "Chapel Hill" ]
    )

// use a module and a value
module MyDataModule =
    let Cities = lazy ( 
        printfn "Loading cities..."
        [ "Raleigh"; "Durham"; "Chapel Hill" ]
     )