読者です 読者をやめる 読者になる 読者になる

by shigemk2

当面は技術的なことしか書かない

case

Haskell

caseそのものについては説明不要ですけど、
書き方はこんな感じ。

case expression of pattern -> result
                      pattern -> result
                      pattern -> result
...

例によって、どのパターンにも引っかからなかったら、ランタイムエラーが発生する。

head'' :: [a] -> a
head'' xs = case xs of [] -> error "Can't call head on empty list, dummy!"
                       (x:_) -> x

describeList :: [a] -> String
describeList ls = "The list is "
                  ++ case ls of [] -> "empty"
                                [x] -> "a singleton list."
                                xs -> " a longer list."

describeList' :: [a] -> String
describeList' ls = "The list is " ++ what ls
  where what [] = "empty"
        what [x] = "a singleton list."
        what xs = "a longer list."
Main> describeList [3, 3, 3]
"The list is  a longer list."
Main> describeList' [3, 3]
"The list is  a longer list."
Main> describeList' []
"The list is empty"
Main> describeList [2]
"The list is a singleton list."