2013-12-09 06:39:11 +00:00
|
|
|
module Lazy ( run, thunk, map, apply, bind
|
2013-12-09 06:01:32 +00:00
|
|
|
) where
|
2013-12-07 20:22:57 +00:00
|
|
|
|
2013-12-09 06:01:32 +00:00
|
|
|
{-| Library for efficient Lazy evaluation.
|
2013-12-07 20:22:57 +00:00
|
|
|
|
|
|
|
-}
|
|
|
|
|
2013-12-09 06:39:11 +00:00
|
|
|
import Basics ((<|), (.))
|
2013-12-07 20:22:57 +00:00
|
|
|
import Native.Lazy
|
|
|
|
|
|
|
|
data Lazy a = L { run : () -> a }
|
|
|
|
|
2013-12-09 06:39:11 +00:00
|
|
|
{-| Memoize a thunk so it is evaluated at most once. -}
|
2013-12-07 20:22:57 +00:00
|
|
|
thunk : (() -> a) -> Lazy a
|
|
|
|
thunk t = L { run = (Native.Lazy.thunk t) }
|
|
|
|
|
2013-12-09 06:39:11 +00:00
|
|
|
{-| Execute a lazy value. -}
|
2013-12-07 20:22:57 +00:00
|
|
|
run : Lazy a -> a
|
2013-12-09 06:01:32 +00:00
|
|
|
run (L r) = r.run ()
|
2013-12-07 20:30:51 +00:00
|
|
|
|
2013-12-09 06:39:11 +00:00
|
|
|
{-| Lazily apply a pure function to a lazy value. -}
|
|
|
|
map : (a -> b) -> Lazy a -> Lazy b
|
|
|
|
map f t = thunk <| \() ->
|
|
|
|
f . run <| t
|
|
|
|
|
|
|
|
{-| Lazily apply a Lazy function to a Lazy value. -}
|
|
|
|
apply : Lazy (a -> b) -> Lazy a -> Lazy b
|
|
|
|
apply f x = thunk <| \() ->
|
|
|
|
(run f) (run x)
|
|
|
|
|
|
|
|
{-| Lazily chain together Lazy computations. -}
|
|
|
|
bind : Lazy a -> (a -> Lazy b) -> Lazy b
|
|
|
|
bind x k = thunk <| \() ->
|
|
|
|
run . k . run <| x
|