Coming from a Scala background I'm pretty used to using tail recursion to write stuff that can't be easily represented using another method. Let's say I want to calculate the length of a list, but I don't want to use a fold. I want to do it in a natural tail recursive way. I thought of this way:
myLength :: [a] -> Int
myLength x = innerLength x 0
innerLength :: [a] -> Int -> Int -- Tail recursive inner call
innerLength [] _ = 0
innerLength (x:xs) n = innerLength xs n+1
and this works fine. But it isn't very readable that innerLength is really the tail recursive inner call to count the list members and it seems like innerLength is scoped in such a way someone could just use innerLength instead of the better myLength.
Is there a better way to do this?
letorwhereclause in the definition ofmyLength.innerLength xs n+1is parsed as(innerLength xs n)+1, this is not tail-recursive.innerLength [] _ = 0throws away the accumulator instead of returning it. It should beinnerLength [] n = n. I'd also be tempted to use strict application in the recursive case e.g.innerLength (_:xs) n = innerLength xs $! n+1