online advertising

Tuesday, June 2, 2015

Haskell 99 Problem 4

Problem:

Please find the problem here.

Solution:

Please see the solution as follow:

The problem give me a chance to practice the accumulator pattern. A more intuitive approach to this problem is simply mylength (x:xs) = 1 + mylength xs. Notice that after the recursion call, there is something else to do (the increment by 1), in other words, the call is not tail recursive. Haskell can optimize tail recursive call by simply jumping to the beginning of the function, but for non tail recursive call that must be done by a real function call, which use up stack space.

The solution to this is essentially saving the information in the next function call's stack frame, as an accumulator.

Also notice how much more elegant the code is without error condition! I just love code that don't have error - wouldn't you?

No comments :

Post a Comment