Skip to content

Instantly share code, notes, and snippets.

@natefaubion
Created January 2, 2021 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natefaubion/4b6d43d0558b44a36fc439de5c68a7a8 to your computer and use it in GitHub Desktop.
Save natefaubion/4b6d43d0558b44a36fc439de5c68a7a8 to your computer and use it in GitHub Desktop.
List/Generator
module Main where
import Prelude
import Data.Array as Array
import Data.Lazy as L
import Partial.Unsafe (unsafePartial)
newtype Producer f a = Producer (f (Step f a))
data Step f a = Cons a (Producer f a) | Nil
class Suspend f where
suspend :: forall a. (Unit -> a) -> f a
force :: forall a. f a -> a
instance suspendFunction :: Suspend (Function Unit) where
suspend = identity
force k = k unit
instance suspendLazy :: Suspend L.Lazy where
suspend = L.defer
force = L.force
type Generator = Producer (Function Unit)
type List = Producer L.Lazy
fromArray :: forall f. Suspend f => Array ~> Producer f
fromArray arr = go 0
where
go ix = Producer $ suspend \_ ->
if ix == Array.length arr then
Nil
else
unsafePartial $ Cons (Array.unsafeIndex arr ix) (go (ix + 1))
view :: forall f. Suspend f => Producer f ~> Step f
view (Producer f) = force f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment