recursionschemelispracketmutual-recursion

Racket two methods referencing each other


I'm doing exercises from The Little Schemer, but I do them in Racket using DrRacket.

One of the exercises has two methods referencing each other. Can this be done in Racket and if so, how?

When trying to do it in DrRacket ide I get an error because the one created higher up in the file can't reference something that comes after. I'm assuming this is because it's being interpreted, but I'm not sure.

Is there a way around this issue?


Solution

  • Yes, this is possible in Racket. It's called "mutual recursion", to give an example, we can define the procedures odd? and even? in terms of each other - not the most efficient way to do it, but just to demonstrate the concept:

    #lang racket
    
    (define (odd? n)
      (if (zero? n)
          #f
          (even? (- n 1))))
    
    (define (even? n)
      (if (zero? n)
          #t
          (odd? (- n 1))))
    

    Maybe you're using a teaching language that forbids referencing procedures not yet defined? click on the bottom-left corner of the window and select "determine language from source", then type #lang racket at the beginning of your code.