Page 1 of 1

Can anyone explain the lambda expression to me?

Posted: Wed Sep 01, 2010 10:10 am
by joybee
:cry:

I just couldn't get it. Here is a simple example and it complains about illegal lambda expression (unknown lisp) or illegal function call (sbcl).

(defvar a 3)
(defvar b 5)
(if (not (equal a b)) ((format t "not equal~%") (setq a 6) (setq b 10)))


Thanks!

Re: Can anyone explain the lambda expression to me?

Posted: Wed Sep 01, 2010 10:25 am
by ramarren
If you use standard (as done more or less automatically by Emacs) formatting (and code tags):

Code: Select all

(defvar a 3)
(defvar b 5)
(if (not (equal a b))
    ((format t "not equal~%") (setq a 6) (setq b 10)))
It becomes obvious that your IF has only one branch, which is a call to function '(format t "not equal~%")'. Since this is a list and does not name a function, it fails with unknown function or invalid lambda expression (the only case where a list is allowed in function position is if it is a lambda expression).

In CL and Lisps in general parentheses are not a grouping operator, but function call operator. If you want to perform a series of actions in sequence, use PROGN form (in CL).

Re: Can anyone explain the lambda expression to me?

Posted: Thu Sep 02, 2010 12:08 pm
by audwinc
joybee wrote: (defvar a 3)
(defvar b 5)
(if (not (equal a b)) ((format t "not equal~%") (setq a 6) (setq b 10)))
I just wanted to elaborate on Ramarren's response. IF has this form:

Code: Select all

(if condition do-this else-do-this)
And functions have this form:

Code: Select all

(function param param param)
Some blocks let you do multiple statements. Others do not. Examples:

Code: Select all

(when t
  (do-one-thing)
  (do-a-second-thing)
  (do-a-third-thing))

(if t
  (do-only-one-thing)
  (do-the-alternative-thing))
Here's a possible fix to your code, assuming you want to format and set a and b:

Code: Select all

(if (not (equal a b))
  (progn
    (format t "not equal~%")
    (setq a 6)
    (setq b 10)))

;; better
(when (not (equal a b))
  (format t "not equal~%")
  (setq a 6)
  (setq b 10))

;; if you meant to set b if a and b ARE equal:
(if (not (equal a b))
  (progn
    (format t "not equal~%")
    (setq a 6))
  (setq b 10))
By the way, progn returns the value of the last function called in its list. If you wanted the first function's value returned, you could use prog1 instead.

~a