Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common Lisp: Working with &rest parameters

Can anyone tell me how to work with the parameters stored in the value specified by &rest.

I've read around a lot and it seems as if authors only know how to list all the parameters as so.

(defun test (a &rest b) b)

This is nice to see, but not really that useful.

The best I've found so far is to use first, second, and so on to get the parameter you are looking for.

(defun test (a &rest b)
    (first b))

I noticed this method stops working at the tenth parameter, but the specification (from what I've read) supports a minimum of 50. Even if the chances are slim that I'll use 50 parameters, I'd like to know how to access them all.

Thanks

like image 292
BlueBadger Avatar asked Mar 10 '09 11:03

BlueBadger


People also ask

What is Common Lisp used for?

Common Lisp sought to unify, standardise, and extend the features of these MacLisp dialects. Common Lisp is not an implementation, but rather a language specification. Several implementations of the Common Lisp standard are available, including free and open-source software and proprietary products.

What software uses Lisp?

Commercial applications of Common Lisp include Grammarly, which uses AI to analyze text and suggest improvements, and Boeing, which uses a server written in the Lisp variant. Lisp Clojure or ClojureScript users include Amazon, Capital One and Walmart.

How do you stop a Lisp from functioning?

To terminate the Lisp system, use the command ":exit" or call the function "(exit)."

Is Common Lisp still used?

Lisp (historically LISP) is a family of programming languages with a long history and a distinctive, fully parenthesized prefix notation. Originally specified in 1958, Lisp is the second-oldest high-level programming language still in common use. Only Fortran is older, by one year.


2 Answers

Rest parameter is just a list. You can handle it using normal list operations.

(defun test (a &rest b))
  (dolist (s b)
    (when (> s 1)
      (print s)
      (do-something-else b)))
like image 85
Marko Avatar answered Oct 18 '22 16:10

Marko


The FIRST, SECOND and so on accessor functions are "just" utility functions on top of CAR/CDR or NTH. SO, I guess, the answer to your specific question is "use NTH or ELT" (or build your own specific acccessor functions).

If you want, you can define an ELEVENTH as:

(defun eleventh (list) (nth 10 list))

I find, however, that I mostly use &REST arguments when there's 0 or more things I want to do something with, not really caring about the specific position of a given argument in the &REST list. That usually entails using LOOP, DO or DOLIST to traverse the arguments and do something with each one; the MAP family or (occasionally) REDUCE.

like image 28
Vatine Avatar answered Oct 18 '22 17:10

Vatine