Omid
Omid

Reputation: 2677

Difficulty understanding nested expressions in Lisp

Here's a function that asks a number and returns the value if its type is indeed a number and else executes the function again:

(defun ask-number ()
  (format t "Please enter a number.~%")
  (let ((val (read)))
    (if (numberp val)
        val
        (ask-number))))

I understand that after the value is read, it is labelled as val and the whole ((val (read))) is an argument of let. What I don't understand is, why the if-statement is nested within let. I would have assumed that the program should be something like this:

(defun ask-number ()
  (format t "Please enter a number.~%")
  (let ((val (read))))
  (if (numberp val)
      val
      (ask-number)))

which leads to an error. I am not sure why this happens.

Upvotes: 1

Views: 226

Answers (1)

C. K. Young
C. K. Young

Reputation: 223183

The reason the if is inside the let is that the val you've created with the let is only valid within the let; once you exit the let, val doesn't exist any more.

let is syntactic sugar for creating and instantly calling a lambda expression, so your let expression is basically the same as:

((lambda (val)
   (if (numberp val)
       val
       (ask-number)))
 (read))

Upvotes: 4

Related Questions