Questions with tail recursion in Haskell

Asked

Viewed 92 times

1

Hello, I would like to know how to base the tail recursion in this language. I did not understand why this 1 in the part: "fatcalda n = fataux n 1". I would like you to help me please!

fatcalda :: Integer -> Integer
fatcalda n = fataux n 1
       where
             fataux n parcial | n == 0 = parcial
                              | n > 0 = fataux (n-1) (n*parcial)

1 answer

1


Assuming you already know what a tail recursion is (in case you didn’t know, I recommend reading it this answer), the argument 1 against there only to ensure that the fataux be called correctly.

In this implementation of fatcalda (or would be fatcauda?), the function that does all the work is fataux, where the second argument is used as the accumulator so that there is a tail recursion. But so that fatcalda properly calculate the value of a factorial, fataux shall always be "initialized" with an accumulator equal to 1. If fataux start with an accumulator with a value other than 1, the result of fatcalda n would be different from n.

It is also important to note that fataux is defined only within the scope of fatcalda and therefore it can only be called by the fatcalda, or another function that may exist in the same scope. How fatcalda n always calls fataux n 1, is guaranteed that the result will be the factorial.

Test yourself in Ghci: set fataux out of fatcalda and test it with the second argument with values other than 1.

Prelude> fataux n parcial | n == 0 = parcial | n > 0 = fataux (n-1) (n*parcial)
Prelude> fatcalda n = fataux n 1
Prelude> fatcalda 5 -- 1*2*3*4*5 = 120 (correto)
120
Prelude> fataux 5 1 -- 1*2*3*4*5 = 120 (correto)
120
Prelude> fataux 5 2 -- 2*2*3*4*5 = 240 (errado)
240
  • That’s right, it would be "fatcauda". Thank you very much, I could understand better on the subject! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.