I wrote this snippet of code and I assume len
is tail-recursive, but a stack overflow still occurs. What is wrong?
myLength :: [a] -> Integer
myLength xs = len xs 0
where len [] l = l
len (x:xs) l = len xs (l+1)
main = print $ myLength [1..10000000]
Remember that Haskell is lazy. Your computation (l+1) will not occur until it's absolutely necessary.
The 'easy' fix is to use '$!' to force evaluation:
myLength :: [a] -> Integer
myLength xs = len xs 0
where len [] l = l
len (x:xs) l = len xs $! (l+1)
main = print $ myLength [1..10000000]