Tail recursions in DAML

G-d willing

Hello,
I have a question about tail recursion.
for example, I want to write a tail recursion that calculates the sum of numbers from 1 to some number.
The following function works:

sumNumbers : Int -> Int
sumNumbers number =
  tailSumNumbers number 0

tailSumNumbers : Int -> Int -> Int
tailSumNumbers number acc
  | number == 0 = acc
  | otherwise = tailSumNumbers (number -1) (acc + number)

However, when I am trying to do it like that it is not working:

sumNumbers : Int -> Int
sumNumbers number =
  tailSumNumbers number 0
    where
      tailSumNumbers number acc
        | number == 0 = acc
        | otherwise = tailSumNumbers (number -1) (acc + number)

And it also does not accept this version

sumNumbers : Int -> Int
sumNumbers number = 
  let tailSumNumbers number acc  
        | number == 0 = acc
        | otherwise = tailSumNumbers (number-1) (acc + number) 
  in 
  tailSumNumbers number 0

The error is:

Failure to process Daml program, this feature is not currently supported.
Local variables defined recursively - recursion can only happen at the top level.

Is it possible to have this solution inside 1 function only, and not 2?

This is a known limitation of Daml that affects general recursion, not just tail recursion.
As the error message tries to explain, only top level functions can be recursive, but not those defined within let or where clauses.

Therefore, if you want to write recursive functions, only the first definition is valid and not the other two.

1 Like