Haskell - コンテキストでの型の操作 - Monad型クラス - Maybe型, bind関数, (>>=)演算子
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)の UNIT5(コンテキストでの型の操作)、LESSON 30(Monad型クラス)、30.5(練習問題)、Q30-3の解答を求めてみる。
コード
sample.hs
main :: IO ()
main = do
mapM_ (\x -> print $ bind x f) [Nothing, Just "", Just "1", Just "2"]
bind :: Maybe a -> (a -> Maybe b) -> Maybe b
bind x f = x >>= (\y -> f y)
f :: String -> Maybe Int
f "" = Nothing
f s = Just (read s)
入出力結果(Terminal, Zsh)
% runghc sample.hs
Nothing
Nothing
Just 1
Just 2
%