r/purescript • • Feb 14 '18
Beginner Question - Tail Recursion
I am working through the PureScript by Example book and I am at the following exercise:
(Medium) Rewrite the following function in tail recursive form using an accumulator parameter:
import Prelude
import Data.Array.Partial (head, tail)
count :: forall a. (a -> Boolean) -> Array a -> Int
count _ [] = 0
count p xs = if p (unsafePartial head xs)
then count p (unsafePartial tail xs) + 1
else count p (unsafePartial tail xs)I have rewritten it in the following way:
count :: forall a. (a -> Boolean) -> Array a -> Int -> Int
count _ [] acc = acc
count p xs acc = if p (unsafePartial head xs)
then count p (unsafePartial tail xs) (acc + 1)
else count p (unsafePartial tail xs) accIs this the correct way to write a tail recursive version?
4
Upvotes
3
u/retief1 Feb 14 '18
That looks correct, yes. I'd quibble about certain style aspects, but you just copied them from the original version, so fair enough.
The critical thing is that you call count and immediately return the result, instead of taking the result of the recursive call and messing with it. If you want to double check this, you can look at the generated javascript. If count compiles to a while loop, you did it right.
3
u/ephrion Feb 14 '18
Generally, recursive "helper" functions are created that pass the initial value in. So you might have:
2
u/kritzcreek Feb 14 '18
The best part is that you can check for yourself! I copied your two solutions into a try.purescript playground here:
Playground
If you check the
Show JSbutton at the top you can take a look at the generated code and see the while loop for the tco'd version.