racketchurch-encoding

Defining a function to represent integers in Church numerals (DrRacket)


I am trying to define a procedure that takes an integer and returns its representation in Church numerals. Could any one please help me figure out the mistake I am making? The following code it's what I have been able to do so far.

(define succ
  (lambda (cn)
    (lambda (f)
      (lambda (x)
        (f ((cn f) x))))))

(define (n->cn n)
  (if (= n 0)
      zero
      (succ (n->cn (lambda (x) (- x 1))))))

When I run the test:

(test (num->cn 3) three)

I am getting the following error:

exception (num->cn 3) at line 107
  expected: <no-expected-value>
=: contract violation
  expected: number?
  given: #<procedure:...ad/racket-file.rkt:99:21>
  argument position: 1st
  other arguments...:
   0

It seems it's expecting a number? but a procedure is given. Which I think matches the intention of the procedure? Thanks for your help and comments for a newbie.


Solution

  • The argument to n->ch should be a number, not a procedure:

    (define (n->cn n)
      (if (= n 0)
          zero
          (succ (n->cn (- n 1)))))