Monday, May 26, 2008

How to pass a list to a function like max or min in LISP

A function like max is defined like this.
(max [number number ...]) and returns the largest of the numbers given

The following works fine and returns 9:
(max 1 5 3 8 4 0 5 9 2)

But if you want to pass the list as a variable you might find that this will not work:
(setq lst '(1 5 3 8 4 0 5 9 2))
(max lst)

; error: bad argument type: numberp: (1 5 3 8 4 0 5 9 2)

The solution is to use the apply function like this:

(setq lst '(1 5 3 8 4 0 5 9 2))
(apply 'max lst)

or if you want to add all values

(setq lst '(1 5 3 8 4 0 5 9 2))
(apply '+ lst)

"Apply" passes a list of arguments to, and executes, a specified function and solves this.

Here are a couple of examples from the help file:

Command: (apply '+ '(1 2 3))
6

Command: (apply 'strcat '("a" "b" "c"))
"abc"

No comments:

Post a Comment

Some of the latest blog posts

Subscribe to RSS headline updates from:
Powered by FeedBurner

Contact Us | About JTB World | Website General Terms of Use | Privacy Policy
^ Top of page

© 2004- JTB World. All rights reserved.