ayman
ayman

Reputation: 63

What (define (p) (p)) does?

I'm reading the "Structure and interpretation of computer programs" 2nd edition in the exercise 1.5, I found a combination that I didn't understand what it does exactly (define (p) (p)).

When I called the procedure (p) I had the cursor blinking in the next line without the ability to write anything .

(define (p) (p))
(p)

I don't know what to expect from this procedure because I defined it by itself.

Upvotes: 6

Views: 606

Answers (2)

alinsoar
alinsoar

Reputation: 15793

(define (p) (p))
(p)

This is syntactic sugar for this

(define p (lamnda () (p))
(p)

After you deepen SICP you will learn that this infinite recursion can also be done so:

((lambda(s) (s s))
 (lambda(s) (display ".") (s s)))

Upvotes: 2

Óscar López
Óscar López

Reputation: 236004

p is a procedure with no parameters. Its body is (p). In Scheme, we call procedures by surrounding them in brackets together with their arguments. Given that p doesn't have parameters, (p) simply calls p. Which calls p. Which calls p... and so on. So what does it do? an infinite loop! and that is all.

Upvotes: 8

Related Questions