模式匹配

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 可以用於任何型別類的任何建構函式。例如,列表的建構函式是:和元組 ,