case of

发布时间 2023-04-07 09:04:09作者: 牧羊龟

函数参数的模式是case of表达式的一种语法替代。这两段代码做同样的事情,并且是可以互换的,如下

head' :: [a] -> a
head' [] = error "empty list~"
head' (x : _) = x

head' :: [a] -> a
head' xs = case xs of [] -> error "empty list~"
                      (x : _) -> x

函数参数的模式只能在定义函数时使用,而case of表达式几乎可以在任何地方使用
如下

describeList :: [a] -> String
describeList xs = "The list is " ++ case xs of [] -> "an empty list"
                                               [x] -> "a unitary list"
                                               xs -> "a long list"

把上面的case of表达式代码转换成函数参数模式,如下

describeList :: [a] -> String
describeList xs = "The list is " ++ what xs
  where what [] = "an empty list"
        what [x] = "an nitary list"
        what xs = "a long list"