elm/libraries/Lazy.elm

35 lines
800 B
Elm
Raw Normal View History

module Lazy ( run, thunk, map, apply, bind
) where
2013-12-07 20:22:57 +00:00
{-| Library for efficient Lazy evaluation.
2013-12-07 20:22:57 +00:00
-}
import Basics ((<|), (.))
2013-12-07 20:22:57 +00:00
import Native.Lazy
data Lazy a = L { run : () -> a }
{-| 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) }
{-| Execute a lazy value. -}
2013-12-07 20:22:57 +00:00
run : Lazy a -> a
run (L r) = r.run ()
2013-12-07 20:30:51 +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