Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct syntax for a lambda expression which gets any number of arguments in Scheme

In Scheme you can define the following procedure:

(define (proc . vars)
        (display (length vars)))

This will allow you to send any amount of args to proc. But when I try to do it this way:

(define proc (lambda (. vars)
        (display (length vars))))

I get the following error:

read: illegal use of "."

I can't seem to find the correct syntax for a lambda expression which gets any number of arguments. Ideas?

(I'm using DrScheme, version 209, with language set to PLT(Graphical))

Thanks!

like image 201
Hila Avatar asked Feb 16 '11 19:02

Hila


2 Answers

The first argument of lambda is the list of arguments:

(define proc (lambda vars
    (display (length vars))))

(proc 1 2 4) ; 3
(proc) ; 0
like image 142
Tim Avatar answered Oct 21 '22 15:10

Tim


The key insight to understanding the (lambda args ...) syntax (that other posters have helpfully posted already) is that a lone non-list item (in this case, args) is a degenerate improper list. Example:

(define a '(arg1 arg2 . rest))
a                   ; => (arg1 arg2 . rest) (improper list of length 2)
(cdr a)             ; => (arg2 . rest)      (improper list of length 1)
(cdr (cdr a))       ; => rest               (improper list of length 0)
like image 34
Chris Jester-Young Avatar answered Oct 21 '22 14:10

Chris Jester-Young