Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Has Anyone Built a Lazy Monad in F#?

I've been reading Chris Okasaki's Purely Functional Data Structures, and am wondering if there is a nice way to build lazy algorithms with F# inside of a monad that enables lazy computation (a Lazy monad). Chris used a custom extension for suspension / force syntax in SML, but I'd like to think that we could instead just use a simple monad in F#. Manual use of lazy and force in F# seems pretty cluttery.

I found this implementation in Scheme, but I don't know how applicable it would be.

From my cursory knowledge and research, it seems both feasible and desirable within reasonable limitations.

Please let me know :)

like image 283
Bryan Edds Avatar asked Feb 21 '23 22:02

Bryan Edds


1 Answers

To port Okasaki code, why not just go with F# lazy keyword and some helper syntax to express forcing, for example:

let (!) (x: Lazy<'T>) : 'T = x.Value

Since F# type system cannot properly express monads, I assume you suggest defining a computation expression for lazy computations. I guess one can do that, but how would that help exactly?

type LazyBuilder =
    | Lazy

    member this.Return(x: 'T) : Lazy<'T> =
        Lazy.CreateFromValue(x)

    member this.Bind(x: Lazy<'T1>, f: 'T1 -> Lazy<'T2>) : Lazy<'T2> =
        lazy (f x.Value).Value

let test () =
    let v =
        Lazy {
            let! x = lazy 1
            let! y = lazy 2
            return x + y
        }
    v.Value


let (!) (x: Lazy<'T>) : 'T = x.Value

let test2 () =
    let v =
        lazy
            let x = lazy 1
            let y = lazy 2
            !x + !y
    !v
like image 102
t0yv0 Avatar answered Mar 07 '23 04:03

t0yv0