Skip to content

Instantly share code, notes, and snippets.

@atton
Last active December 21, 2015 05:49
Show Gist options
  • Save atton/6260105 to your computer and use it in GitHub Desktop.
Save atton/6260105 to your computer and use it in GitHub Desktop.
HookMonad. but it's not satisfy Monad Law
data HookMonad a = Hook (a -> a) a
instance Monad HookMonad where
return = Hook id
Hook h x >>= f = f . h $ x
nonMinusPoint = Hook (\x -> if x < 0 then 0 else x)
getValue (Hook f x) = f x
add :: Integer -> Integer -> HookMonad Integer
add n m = nonMinusPoint $ n + m
multi :: Integer -> Integer -> HookMonad Integer
multi n m = nonMinusPoint $ n * m
{-
*Main> getValue $ foldl (>>=) (nonMinusPoint 0) [(add 1), (add (-2)), (add (-3)), (add 10)]
10
*Main> fmap getValue $ scanl (>>=) (nonMinusPoint 0) [(add 1), (add (-2)), (add (-3)), (add 10)]
[0,1,0,0,10]
*Main> getValue $ foldl (>>=) (nonMinusPoint 0) [(add 1), (multi 100), (multi (-1)), (add 20)]
20
*Main> fmap getValue $ scanl (>>=) (nonMinusPoint 0) [(add 1), (multi 100), (multi (-1)), (add 20)]
[0,1,100,0,20]
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment