計算機科学のブログ

実践Haskell HaskellのエラーとEither型 部分関数、Enum、リスト、succ関数、tail関数、last関数、安全な版、Myabe、コンストラクタ、Just、Nothing、Left、Right

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT7(実践Haskell)、LESSON 38(HaskellのエラーとEither型)、38.5(練習問題)Q38-2の解答を求めてみる。

コード

safeSucc :: (Enum a, Eq a, Bounded a) => a -> Maybe a
safeSucc x = if x /= maxBound
             then Just (succ x)
             else Nothing

safeTail :: [a] -> [a]
safeTail [] = []
safeTail (x:xs) = xs

safeLast :: [a] -> Either String a
safeLast [] = Left "empty list"
safeLast xs = Right (last xs)


main :: IO ()
main = do
    print "succ"
    mapM_ (print . safeSucc)
          ([1, maxBound] :: [Int])
    print "tail"
    mapM_ (print . safeTail)
          [[], [1], [1..5]]
    print "last"
    mapM_ (print . safeLast)
          [[], [1], [1..5]]

入出力結果(Terminal, Zsh)

% runghc sample2.hs
"succ"
Just 2
Nothing
"tail"
[]
[]
[2,3,4,5]
"last"
Left "empty list"
Right 1
Right 5
%