カスタムlength
関数での古典的な最初の試みを次に示します。
length1 [] = 0
length1 (x:xs) = 1 + length1 xs
そして、ここに末尾再帰バージョンがあります:
length2 = length2' 0 where
length2' n [] = n
length2' n (x:xs) = length2' (n+1) xs
ただし、(n+1)
厳密に評価されるわけではありませんが、代わりに Haskell はサンクを作成しますよね?
これは、サンクの作成を防ぎ、厳密な評価を強制する正しい方法(n+1)
ですか?
length3 = length3' 0 where
length3' n [] = n
length3' n (x:xs) = length3' (n+1) $! xs
seq
の代わりに同じ効果を得るにはどうすればよい$!
ですか?