分別使用 Functor, Applicative, Monad 方式轉換字元串大小寫及順序
module Main whereimport Data.Charcap :: String -> Stringcap xs = fmap toUpper xsrev :: String -> Stringrev = reverse -- 1, 函數組合方式composed :: String -> Stringcomposed = cap . rev --2, functor 方式{--這裡 rev 是個 Functor, F a (->) String 是 F 第二個參數 String 是 a--}fmapped :: String -> Stringfmapped = fmap cap rev--3, applicative 方式tupled :: String -> (String, String)tupled = (,) <$> cap <*> rev--3, monad的do方式{-- monad 方式的tupled --}tupledMonadic :: String -> (String, String)tupledMonadic = do c <- cap r <- rev return (c, r)--4, monad的>>=方式tupledMonadic_ :: String -> (String, String)tupledMonadic_ = cap >>= c-> rev >>= r -> return (c, r)main :: IO ()main = do putStrLn $ composed "hello world" putStrLn $ fmapped "reverse and capital" putStrLn $ show $ tupled "hi" putStrLn $ show $ tupledMonadic "tu" putStrLn $ show $ tupledMonadic_ "tu"
推薦閱讀:
TAG:Haskell | monad | ApplicativeFunctor |