Abdelhamid Sajid
Abdelhamid Sajid

Reputation: 69

How can I define a function using unkown number of variables?

I am studying Lisp for the first time and I was working on a simple function that append two lists. As I was testing the functualities of the predifined append, I noticed that I can give it more than two list and I wondered how to do it myself? So I wonder how to make a function in Lisp that take an unknown number of variables?

Upvotes: 2

Views: 548

Answers (2)

sds
sds

Reputation: 60004

Use the &rest lambda list keyword:

(defun test-rest (a &rest b)
  (format t "1st argument: ~S; 2nd argument: ~S; other arguments: ~S~%"
          a (first b) (rest b)))

Now (test-rest 1 2 3 4) prints

1st argument: 1; 2nd argument: 2; other arguments: (3 4)

If you are interested specifically in Scheme, you can use use a dotted arglist:

(define (test-rest a . b) 
  (display (list (list "first" a) 
                 (list "others" b))))

Now (test-rest 1 2 3 4) will print

((first 1) (others (2 3 4)))

Upvotes: 3

rsm
rsm

Reputation: 2560

You can define function using dotted list for optional arguments. All optional arguments will be passed as a list to your function.

So for example this function takes one mandatory argument a0 and any number of optional arguments passed as a-rest list:

(define (take-many a0 . a-rest)
  a-rest)

Now, when you call it:

(take-many 1 20 333)

=> (20 333)

you can see that optional second and thind argument are available as a list. To access them, you use standard list accessors like car, cdr, nth etc.

The same goes for lambda.

You can read more about it on Dr Racket: 3.8 Procedure Expressions: lambda and lambda-case (look for rest-id).

Upvotes: 4

Related Questions