-- monada za vhodni kanal data Input i a = In { run :: [i] -> (a, [i]) } consume :: Input i i consume = In (\input -> (head input, tail input)) instance Functor (Input i) where -- fmap :: (a -> b) -> Input i a -> Input i b fmap f xi = In (\input -> let (x, input') = run xi input in (f x, input')) instance Applicative (Input i) where pure x = In (\input -> (x, input)) (In frun) <*> (In xrun) = In (\input -> let (f, input') = frun input (x, input'') = xrun input' in (f x, input'')) instance Monad (Input i) where -- (>>=) :: Input i a -> (a -> Input i b) -> Input i b ai >>= f = In (\input -> let (a, input') = run ai input in run (f a) input') primer1 = do x <- consume y <- consume return ("First input: " ++ x ++ " Second input: " ++ y) -- monada za izhodni kanal data Output o a = Out { result :: a, output :: o } deriving Show instance Functor (Output o) where -- fmap :: (a -> b) -> Output o a -> Output o b fmap f (Out x o) = Out (f x) o instance Monoid o => Applicative (Output o) where -- pure :: a -> Output o a pure x = Out x mempty -- (<*>) :: Output o (a -> b) -> (Output o a) -> Output o b Out f o <*> Out x o' = Out (f x) (mappend o o') instance Monoid o => Monad (Output o) where -- (>>=) :: Output o a -> (a -> Output o b) -> Output o b Out x o >>= f = let (Out y o') = f x in Out y (mappend o o') write :: o -> Output o () write x = Out () x primer2 = do write "Hello," x <- return 10 write " world" y <- return (x + 20) write "!" return (x * y) isPrime :: Int -> Bool isPrime k = all (\i -> k `mod` i /= 0) [i | i <- [2..(k `div` 2)]] primes :: Int -> [Int] primes n = output (loop 2) where loop k | k >= n = return () | otherwise = do if isPrime k then write [k] else return () loop (k + 1) -- primer3 = do write "What is your name? " -- name <- consume -- write "Hello, " ++ name