Haskell tail recursion predictability
One of the biggest issues I have with haskell is to be able to (correctly) predict the performance of has开发者_运维知识库kell code. While I have some more difficult problems, I realize I have almost no understanding.
Take something simple like this:
count [] = 0
count (x:xs) = 1 + count xs
As I understand it, this isn't strictly a tail call (it should need to keep 1 on the stack), so looking at this definition -- what can I reason about it? A count function should obviously have O(1) space requirements, but does this one? And can I be guaranteed it will or won't?
if you want to reason more easily about recursive functions, use higher order functions with known time nd space complexity. If you use foldl or foldr you know that their space complexity cannot be O(1). But if you use foldl' from Data.List as in
count = foldl' (\acc x -> acc + 1) 0
your function will be O(1) in space complexity as foldl' is tail recursive per definition.
HTH Chris
精彩评论