Can anyone explain the lambda expression to me?

Whatever is on your mind, whether Lisp related or not.
Post Reply
joybee
Posts: 21
Joined: Wed Jan 07, 2009 1:49 pm

Can anyone explain the lambda expression to me?

Post by joybee » Wed Sep 01, 2010 10:10 am

: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!

ramarren
Posts: 613
Joined: Sun Jun 29, 2008 4:02 am
Location: Warsaw, Poland
Contact:

Re: Can anyone explain the lambda expression to me?

Post by ramarren » Wed Sep 01, 2010 10:25 am

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).

audwinc
Posts: 12
Joined: Thu Sep 02, 2010 11:46 am

Re: Can anyone explain the lambda expression to me?

Post by audwinc » Thu Sep 02, 2010 12:08 pm

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

Post Reply