Loading

Paste #p7l029ukh

  1. data IO a =
  2.     Pure a
  3.     Write String (IO a)
  4.     Read (String -> IO a)
  5.  
  6. -- useful primitives
  7. read = Read $ \s -> Pure s
  8.  
  9. write :: String -> IO ()
  10. write s = Write s $ Pure ()
  11.  
  12. instance Functor (IO a) where
  13.     fmap f (Pure a) = Pure $ f a
  14.     fmap f (Write s io) = Write s $ fmap f io
  15.     fmap f (Read m) = Read $ \s -> fmap f (m s)
  16.  
  17. instance Applicative (IO a) where
  18.     pure a = Pure a
  19.     Pure f <*> io = fmap f io
  20.     Write s io <*> io' = Write s (io <*> io')
  21.     Read m <*> io = Read $ \s -> ((m s) <*> io)
  22.  
  23. instance Monad (IO a) where
  24.     Pure a >>= k = k a
  25.     Write s io >>= k = Write s (io >>= k)
  26.     Read m >>= k = Read $ \s -> ((m s) >>= k)
  27.  
  28. main :: IO ()
  29. main = do
  30.     line <- read
  31.     myIf (line == "hi") (write "true") (write "false")