10

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!

Hila
  • 1,080
  • 1
  • 9
  • 22
  • Unrelated to your question, I strongly encourage you to upgrade to the latest version of DrScheme, now called DrRacket. You can download it here: http://racket-lang.org/ – Sam Tobin-Hochstadt Feb 21 '11 at 14:44
  • @SamTH The version of DrScheme I used was dictated by my university, but thanks, anyway - I may finish reading SICP on my free time and use this version instead... – Hila Feb 21 '11 at 17:14

3 Answers3

15

The first argument of lambda is the list of arguments:

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

(proc 1 2 4) ; 3
(proc) ; 0
haziz
  • 12,994
  • 16
  • 54
  • 75
Tim
  • 13,904
  • 10
  • 69
  • 101
  • Lambda is a special form, and it's a mistake to call the second thing in a lambda form the "first argument". Sorry, captain pedantic here. – John Clements Feb 18 '11 at 04:13
  • @John: What would you call it? – Tim Feb 18 '11 at 07:53
  • I would probably call it "the second element of the lambda form." The problem with the word "argument" is that it's inextricably associated with function calling. – John Clements Feb 19 '11 at 05:39
6

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)
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • 2
    Just to clarify: the degenerate list `(a1 a2 . args)` would, without a1 and a2, simply be `args`. A degenerate list is one that lacks the ending pair with a nil. – Tim Feb 16 '11 at 20:07
  • 3
    @Tim: The proper term for a list that lacks a `'()` end is an _improper list_. A _degenerate_ improper list is one that ceases to even look like a list, not even an improper one. – C. K. Young Feb 16 '11 at 20:09
  • I didn't know of the distinction between _improper_ and _degenerate_. Thanks. – Tim Feb 16 '11 at 20:46
1

You should omit the parentheses on lambda's argument list to denote a variable number of arguments:

(define proc (lambda vars
    (display (length vars))))
Jeff Ames
  • 2,044
  • 13
  • 18