I was trying to learn a bit more on computation expressions, and wanted to write my own minimalistic expression builder. Just to get the feel for it.
I decided to give a shot at making an expression builder for the Lazy<’T> type. Sure, this wouldn’t give much benefit, just a more smooth way och combining lazies without constantly accessing the Value property.
Here is what I came up with:
open System
let bind (x : Lazy<'a>) (f : 'a -> Lazy<'b>) = lazy f(x.Value).Value
type LazyBuilder() =
member this.Bind(x : Lazy<'a>, f : 'a -> Lazy<'b>) = bind x f
member this.Return<'T> (x : 'T) : Lazy<'T> = Lazy.CreateFromValue x
let lz = LazyBuilder()
let readNumber() = lazy (
Console.WriteLine "Enter a number:"
let v = Console.ReadLine()
Double.Parse v)
let l = lz{
let! x = readNumber()
let! y = readNumber()
return x * y
}
Console.WriteLine "before execution"
Console.WriteLine ("Result: " + l.Value.ToString())
Console.ReadKey() |> ignore
let bind (x : Lazy<'a>) (f : 'a -> Lazy<'b>) = lazy f(x.Value).Value
type LazyBuilder() =
member this.Bind(x : Lazy<'a>, f : 'a -> Lazy<'b>) = bind x f
member this.Return<'T> (x : 'T) : Lazy<'T> = Lazy.CreateFromValue x
let lz = LazyBuilder()
let readNumber() = lazy (
Console.WriteLine "Enter a number:"
let v = Console.ReadLine()
Double.Parse v)
let l = lz{
let! x = readNumber()
let! y = readNumber()
return x * y
}
Console.WriteLine "before execution"
Console.WriteLine ("Result: " + l.Value.ToString())
Console.ReadKey() |> ignore
It yields output like this:
before execution Enter a number: 67 Enter a number: 3 Result: 201 Press a key to quit
Inga kommentarer:
Skicka en kommentar