0

I have defined Church numeral zero and some other standard functions on church numerals according to Wikipedia definitions as following:

(define n0 (λ (f x) x))

(define newtrue
  (λ(m n) m))

(define newfalse
  (λ(m n) n))

(define iszero
  (λ(m) (m (λ(x) newfalse) newtrue)))

(define ifthenelse
  (λ(a b c) (a b c)))

Using these, I write a recursion loop as:

(((λ(r) (λ(n) (ifthenelse (iszero n) n ((r r) n))))
   (λ(r) (λ(n) (ifthenelse (iszero n) n ((r r) n))))) n0)

Now for argument n0 as above, this should return n0, without going into recursion. But it doesn't. Why?

Note 1: This recursion loop works perfectly fine with ordinary numerals and ordinary functions:

(((λ(r) (λ(n) (if (= 0 n) n ((r r) n))))
   (λ(r) (λ(n) (if (= 0 n) n ((r r) n))))) 0)

This returns 0 as it should.

Note 2: Functions ifthenelse, iszero, newtrue, newfalse also work fine on their own.

1 Answers1

0

The reason for the loop is that the semantics of functions in Scheme is to always evaluate all its arguments.

In your second example:

(((λ(r) (λ(n) (if (= 0 n) n ((r r) n))))
   (λ(r) (λ(n) (if (= 0 n) n ((r r) n))))) 0)

you are using if, which is a special form that does not evaluate the third argument if the condition is true. So, it evaluates (= 0 n) and returns immediately 0, since the condition is #true, without evaluating the third argument ((r r) n).

Instead, in the first example:

(((λ(r) (λ(n) (ifthenelse (iszero n) n ((r r) n))))
   (λ(r) (λ(n) (ifthenelse (iszero n) n ((r r) n))))) n0)

ifthenelse is a function, so that, according to the evaluation rules of Scheme, all its arguments are evaluated, including ((r r) n), and this causes an endless loop.

Renzo
  • 26,848
  • 5
  • 49
  • 61