Skip to content

Instantly share code, notes, and snippets.

@TomasMikula
Last active October 6, 2023 12:14
Show Gist options
  • Save TomasMikula/6ea328eb446b8e7c9057d7406ab002f3 to your computer and use it in GitHub Desktop.
Save TomasMikula/6ea328eb446b8e7c9057d7406ab002f3 to your computer and use it in GitHub Desktop.
Demo: Lazy evaluation of the writer monad

The output from ghci demonstrates that wa >>= f produces the result even though wa contains diverging computations.

% ghci lazy-writer.hs
GHCi, version 9.4.4: https://www.haskell.org/ghc/  :? for help
[1 of 2] Compiling Main             ( lazy-writer.hs, interpreted )
Ok, one module loaded.
ghci> go
False, 42
ghci> 
data Wr w a = Wr w a
a ⅋⅋ b = b && a
instance Functor (Wr Bool) where
fmap f (Wr w a) = (Wr w (f a))
instance Applicative (Wr Bool) where
pure a = Wr True a
(Wr v f) <*> (Wr w a) = Wr (v ⅋⅋ w) (f a)
instance Monad (Wr Bool) where
(Wr v a) >>= f = let (Wr w b) = f a in Wr (v ⅋⅋ w) b
instance Show a => Show (Wr Bool a) where
show (Wr w a) = (show w) <> ", " <> (show a)
zzz :: forall a. a
zzz = zzz
wa :: Wr Bool Int
wa = Wr zzz zzz
f :: Int -> Wr Bool Int
f n = Wr False 42
go = wa >>= f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment