module Examples
where
import Data.Char ( isDigit)
--
mb1 :: Int -> Maybe String
mb1 i
| i >= 0 = Just (show i)
| otherwise = Nothing
mb2 :: String -> Maybe String
mb2 "" = Nothing
mb2 s = Just (tail s)
mb3 :: String -> Maybe Int
mb3 "" = Nothing
mb3 s
| all isDigit s = Just (read s)
| otherwise = Nothing
mb :: Int -> Maybe Int
mb = mf3 mb1 mb2 mb3
mbtests :: [Maybe Int]
mbtests = map mb [0, 1, 12, 123, 1234]
--
mf1 :: Monad m =>
(a -> m b) -> (b -> m c) -> (c -> m d) -> (a -> m d)
mf1 f1 f2 f3
= \ x -> f1 x >>= f2 >>= f3
mf2 :: Monad m =>
(a -> m b) -> (b -> m c) -> (c -> m d) -> (a -> m d)
mf2 f1 f2 f3 x
= do x1 <- f1 x
x2 <- f2 x1
x3 <- f3 x2
return x3
(>=>) :: Monad m =>
(a -> m b) -> (b -> m c) -> (a -> m c)
f >=> g
= \ x -> f x >>= g
mf3 :: Monad m =>
(a -> m b) -> (b -> m c) -> (c -> m d) -> (a -> m d)
mf3 f1 f2 f3
= f1 >=> f2 >=> f3
--
io1 :: Int -> IO String
io1 i
= do print i
return $ show i
io2 :: String -> IO String
io2 ""
= return "---"
io2 [_]
= return "+++"
io2 s
= do print s
return $ tail s
io3 :: String -> IO Int
io3 s
= do print s
return $ length s
io :: Int -> IO Int
io = mf3 io1 io2 io3
iotests :: IO ()
iotests = sequence_ $ map io [0, 1, 12, 123, 1234]
--
l1 :: Int -> [Int]
l1 i
| i < 0 = []
| otherwise = map (read . (:[])) . show $ i
l2 :: Int -> [Int]
l2 i
= [i - 1, i + 1]
l3 :: Int -> [String]
l3 = return . show
ls :: Int -> [String]
ls = mf3 l1 l2 l3
lstests :: [[String]]
lstests = map ls [-1, 0, 1, 12, 123, 1234]