[英]Haskell pattern matching gone wrong
我正在學習一些Haskell,我試圖了解模式匹配的工作原理。 這樣做,我寫了一個簡單的nth
函數。
nth' :: Integer -> [a] -> a
nth' n [] = error "Index out of bound"
nth' n (x:xs) = if n == 0 then x else nth' (n - 1) xs
第一個實現似乎按預期工作。
-- nth' 25 ['a'..'z']
-- 'z'
-- nth' 26 ['a'..'z']
-- *** Exception: Index out of bound
但是,當我重構它用模式匹配替換if語句時,我最終得到“索引越界”異常,我顯然不應該這樣做。
nth' :: Integer -> [a] -> a
nth' _ [] = error "Index out of bound"
nth' 0 (x:[]) = x
nth' n (_:xs) = nth' (n - 1) xs
-- nth' 2 ['a'..'z']
-- *** Exception: Index out of bound
我究竟做錯了什么?
模式x:[]
匹配包含一個元素的列表。 因此,只有當第一個參數為0且第二個參數是單元素列表時,才會執行nth' 0 (x:[])
大小寫。 如果第二個參數是一個包含多個參數的列表,那么它將進入最后一個案例。
您需要將第二種情況更改為nth' 0 (x:_) = x
,以便無論列表中有多少元素(只要它至少有一個),它就會匹配。
有問題的條款:
nth' 0 (x:[]) = x
它只匹配一個元素列表。 嘗試改變它:
nth' 0 (x:_) = x
嘗試:
nth' :: Integer -> [a] -> a
nth' _ [] = error "Index out of bound"
-- nth' 0 (x:[]) = x -- matches one element list x:[] = [x]
nth' 0 (x:_) = x -- matches first element and everything (not just empty list)
nth' n (_:xs) = nth' (n - 1) xs
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.