Has anyone created a lazy monad in F #?

I read Chris Okasaki Purely functional data structures , and I wonder if there is a good way to create lazy algorithms with F # inside the monad that gives lazy calculations (lazy monad). Chris used a custom extension for the suspension / syntax syntax in SML, but I would like to think that instead we could just use the simple monad in F #. The manual use of laziness and power in F # seems rather messy.

I found this implementation on the Scheme, but I do not know how applicable it is.

From my cursory knowledge and research, it seems reasonable and desirable to a reasonable extent.

Please let me know:)

+4
source share
2 answers

To output Okasaki code, why not just go with the F # lazy keyword and some helper syntax for expressing forcing, for example:

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

Since a system like F # cannot correctly express monads, I assume that you are proposing to define a calculation expression for lazy calculations. I think it can be done, but how exactly will it help?

 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 
+7
source

I'm not sure if this helps, but you can generally avoid using the lazy keyword if you really want for some reason:

 type ('a, 'b) lazyT = Lz of 'a * ('a -> 'b) let force (Lz (a, e)) = ea let pack x = Lz(x, (fun i -> i)) type MyLazyBuilder = | Mylazy member this.Bind(x, f) = match x with | Lz(xa, xe) -> Lz(xa, fun x -> force (f (xe x))) member this.Return(x) = pack x let sth = Mylazy { let! x = pack 12 let! y = pack (x + 1) return y * x } let res = force sth 

(there is no part where the force only evaluates it once).

Late, but thought it was worth the suggestion.

+1
source

Source: https://habr.com/ru/post/1389832/


All Articles