模式匹配

Haskell 在函数定义和 case 语句中都支持模式匹配表达式。

case 语句很像其他语言中的 switch,除了它支持所有 Haskell 的类型。

让我们开始简单:

longName::String -> String
longName name = case name of
                   "Alex"  -> "Alexander"
                   "Jenny" -> "Jennifer"
                   _       -> "Unknown"  -- the "default" case, if you like

或者,我们可以将函数定义为一个模式匹配的方程式,只需不使用 case 语句:

longName "Alex"  = "Alexander"
longName "Jenny" = "Jennifer"
longName _       = "Unknown"

一个更常见的例子是 Maybe 类型:

data Person = Person { name::String, petName :: (Maybe String) }

hasPet::Person -> Bool
hasPet (Person _ Nothing) = False
hasPet _ = True  -- Maybe can only take `Just a` or `Nothing`, so this wildcard suffices

模式匹配也可用于列表:

isEmptyList :: [a] -> Bool
isEmptyList [] = True
isEmptyList _  = False

addFirstTwoItems :: [Int] -> [Int]
addFirstTwoItems []        = []
addFirstTwoItems (x:[])    = [x]
addFirstTwoItems (x:y:ys)  = (x + y) : ys

实际上,Pattern Matching 可以用于任何类型类的任何构造函数。例如,列表的构造函数是:和元组 ,