私は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 ステートメントをパターン マッチングに置き換えてリファクタリングすると、明らかにすべきではない "Index out of bound" 例外が発生します。
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
私は何を間違っていますか?