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) acc

Is this the correct way to write a tail recursive version?

4 Upvotes

6 comments sorted by

View all comments

Show parent comment

1

u/[deleted] Feb 14 '18

Awesome, thanks - I didn't think to look at the generated JS to check for the while loop!