Created
February 15, 2025 11:00
-
-
Save SchlenkR/07f1a8057b1cd891e6d906c833637a8c to your computer and use it in GitHub Desktop.
F# lazy CE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type NoYieldedValue = NoYieldedValue | |
type OneYieldedValue<'a> = OneYieldedValue of 'a | |
type JayzBuilder() = | |
// it all starts here ..., | |
member _.Zero() = NoYieldedValue | |
// we can cause side effects as long as no other value is yielded | |
member _.Combine(NoYieldedValue, NoYieldedValue) = NoYieldedValue | |
// once a value is yielded, we change the type that flows through the computation | |
// to `OneYieldedValue`. Since we have no methods defined on the builder that can | |
// operate on `OneYieldedValue`, except of `Delay`, which will end the computation | |
// on a call to `Run`. | |
member _.Combine(NoYieldedValue, OneYieldedValue b) = b | |
member _.Yield(value: 'a) = OneYieldedValue value | |
// pass the delayed computation through to the `Run` methods | |
member _.Delay(f: unit -> _) = f | |
// 1) we support lazy computations that emits nothing (map from `NoYieldedValue` to `unit`) | |
member _.Run(f: unit -> NoYieldedValue) = Lazy(()) | |
// 1) we support lazy computations with one arbitrary yielded value | |
member _.Run(f: unit -> OneYieldedValue<'a>) = | |
Lazy<'a>(fun () -> | |
let (OneYieldedValue value) = f () | |
value | |
) | |
let jayz = JayzBuilder() | |
// ---------------------------------------- | |
let lazyValue = | |
jayz { | |
printfn "OHHH (1) Performing heavy computation..." | |
printfn "OHHH (2) Performing heavy computation..." | |
42 | |
} | |
printfn "Before forcing lazyValue... (no heavy computation yet!)" | |
printfn "Forcing lazyValue: %d" lazyValue.Value | |
let lazyValue2 = | |
lazy | |
printfn "OHHH (1) Performing heavy computation..." | |
printfn "OHHH (2) Performing heavy computation..." | |
42 | |
printfn "Before forcing lazyValue2... (no heavy computation yet!)" | |
printfn "Forcing lazyValue2: %d" lazyValue2.Value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment