Last active
August 29, 2015 14:26
-
-
Save benjumanji/15b1ddb05ea1d40df5c2 to your computer and use it in GitHub Desktop.
Quick and cheesy fresh id generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main where | |
main :: IO () | |
main = let strings = evalSupply examples 0 | |
-- will print | |
-- got: 0 | |
-- got: 1 | |
in mapM_ putStrLn strings | |
data Cnt a = Cnt (Int -> (Int, a)) | |
instance Functor Cnt where | |
fmap f (Cnt k) = Cnt $ \s -> | |
let (s', a) = k s | |
in (s', f a) | |
instance Applicative Cnt where | |
pure a = Cnt $ \s -> (s, a) | |
Cnt kf <*> Cnt km = Cnt $ \s -> | |
let (s', f) = kf s | |
(s'', m) = km s' | |
in (s'', f m) | |
instance Monad Cnt where | |
return = pure | |
Cnt k >>= f = Cnt $ \s -> | |
let (s', a) = k s | |
Cnt k' = f a | |
in k' s' | |
supply :: Cnt Int | |
supply = Cnt $ \s -> (s + 1, s) | |
evalSupply :: Cnt a -> Int -> a | |
evalSupply (Cnt k) s = snd $ k s | |
example :: Cnt String | |
example = do | |
i <- supply | |
return $ "got: " ++ show i | |
examples :: Cnt [String] | |
examples = do | |
a <- example | |
b <- example | |
return [a, b] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment