Floofk
Floofk

Reputation: 113

Why does Setq work but not let?

I'm following the syntax as it is in my book "The land of lisp" and the let version only returns nil when passed *string*. Whereas the "setq" version returns the reversed version of string.

(defparameter *string* "a b c")
(defun reverse-string (string)
    (let (reversed (string))))

(defun setq-reverse-string (string)
    (setq reversed (reverse string)))

Upvotes: 0

Views: 117

Answers (1)

Barmar
Barmar

Reputation: 780724

The syntax of LET is:

(LET ((var1 val1)
      (var2 val2)
      ...)
  body)

In place of (varN valN) you can just put varN, which is shorthand for (varN nil). You can also omit valN, in which case it defaults to nil.

So your code is equivalent to:

(defun reverse-string (string)
  (let ((reversed nil)
        (string nil))))

You're missing a level of parentheses to do what you want:

(defun reverse-string (string)
  (let ((reversed (string)))))

You're also missing the call to reverse, and returning the variable

(defun reverse-string (string)
  (let ((reversed (reverse string)))
    reversed))

Upvotes: 2

Related Questions