Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

lisp

scheme

sicp

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.

like image 569
ayman Avatar asked Jul 07 '19 10:07

ayman


2 Answers

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.

like image 85
Óscar López Avatar answered Sep 21 '22 17:09

Óscar López


(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)))
like image 44
alinsoar Avatar answered Sep 18 '22 17:09

alinsoar