6 people like it.

Lazy variable

When we need lazy evaluation, we use the Lazy<'T>. However, the Lazy<'T> must evaluate explicitly. This example enables implicit evaluation(call-by-need).

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
type MyClass() =
    do printfn "(created !)"
    member self.Print(msg) = printfn "%s" msg

let lazyMyClass = lazy (MyClass())
let instance<'dummy> = lazyMyClass.Value

[<EntryPoint>]
let main _ =
    printfn "F#!F#!"
    instance.Print("First")
    instance.Print("Second")
    0

// Output:
// F#!F#!
// (created !)
// First
// Second
Multiple items
type MyClass =
  new : unit -> MyClass
  member Print : msg:string -> unit

Full name: Script.MyClass

--------------------
new : unit -> MyClass
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val self : MyClass
member MyClass.Print : msg:string -> unit

Full name: Script.MyClass.Print
val msg : string
val lazyMyClass : Lazy<MyClass>

Full name: Script.lazyMyClass
val instance<'dummy> : MyClass

Full name: Script.instance
property System.Lazy.Value: MyClass
Multiple items
type EntryPointAttribute =
  inherit Attribute
  new : unit -> EntryPointAttribute

Full name: Microsoft.FSharp.Core.EntryPointAttribute

--------------------
new : unit -> EntryPointAttribute
val main : string [] -> int

Full name: Script.main
Raw view Test code New version

More information

Link:http://fssnip.net/8C
Posted:13 years ago
Author:Nobuhisa
Tags: lazy