10

Let's say I've written a function in Haskell and I want to assert that it is tail-recursive and it will be optimized by the compiler. Is there a way to do it?

I know there's a way to do it in Scala with @tailrec annotation.

Example:

import scala.annotation.tailrec

class Factorial2 {
  def factorial(n: Int): Int = {
    @tailrec def factorialAcc(acc: Int, n: Int): Int = {
      if (n <= 1) acc
      else factorialAcc(n * acc, n - 1)
    }
    factorialAcc(1, n)
  }
}
Mysquff
  • 293
  • 4
  • 11
  • 8
    Tail recursion doesn't have such big significance in Haskell due to lazy evaluation. In fact, in some circumstances tail-recursive functions are actually _worse_ than non-tail recursive. – Fyodor Soikin Mar 05 '19 at 00:49
  • 1
    Tail recursion optimization happens automatically. It is pretty straightforward for the compiler to automatically detect that a function is tail recursive, under any circumstance I can think of. I don't think it is possible to write a tail recursive function that will not already be automatically recognized and optimized by GHC. I suspect the reason Scala has the annotation is that the tail recursion optimization can lose some call stack info when debugging (whether this is actually bad is a bit debatable, I'd say). Also, what @FyodorSoikin said is important, with regard to lazy evaluation. – David Young Mar 05 '19 at 00:59
  • 8
    I think the point is not to ensure that the compiler realizes the function is tail-recursive, but to make sure the *programmer* realizes when they have accidentally written a non-tail-recursive function. So, not "please optimize this", which is redundant, but "please notify me if this cannot be optimized". Of course it is rarer to want tail-recursive functions in Haskell, but it is not unheard of, and it could be useful to confirm that you have written one. – amalloy Mar 05 '19 at 02:22
  • @amalloy - Yes, that's what I meant. Sorry if my post wasn't clear enough. – Mysquff Mar 05 '19 at 15:47

1 Answers1

1

As for GHC 8.8.2 tail recursion cannot be forcefully asserted by any pragma or keyword.

radrow
  • 6,419
  • 4
  • 26
  • 53