我正在學習一些Haskell,我試圖讓我的頭瞭解模式匹配是如何工作的。 這樣做,我寫了一個簡單的nth
函數。Haskell模式匹配出錯了
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
我在做什麼錯?
權......這就是爲什麼'第n個」 25 'A' .. 'Z']'不實際返回 'Z'! 非常感謝! – 2013-03-09 16:28:39