Search code examples
schemerackettail-recursion

Why does DrRacket seem to identify this as a tail call?


Consider this snippet:

#lang racket

(define (f i)
  (if (> i 5)
      0
      (+ 1 (f (+ 1 i)))))

Here, the call to f is not in tail position, and when I debug, I see a growing stack of the form

(+ ...)
(f ...)
(f ...)
(f ...)
(f ...)

This is expected. However, when I hover over the beginning of the last line, a light purple arrow appears and points to the beginning of the function definition. If I understand the documentation correctly, it indicates tail position. What am I missing?


Solution

  • The form which is the last line is in tail position with respect to f. The recursive call to f, however, isn't: if you hover over the f you'll get a pale blue arrow which tells you that it's the same f the function is binding. Here's a screenshot showing both things:

    arrows

    All of the (if ...) form and both of its consequents are in tail position. The f is the same f defined by the function, but is not in tail position.