3

I recently started using ChickenScheme and now I want to declare a function with default argument (if not specified). I found this example on the Racket site, I know Racket and ChickenScheme are different but I thought that these basic things were the same.

(define greet
  (lambda (given [surname "Smith"])
    (string-append "Hello, " given " " surname)))

This is the error from the ChickenScheme interpreter:

Error: during expansion of (lambda ...) - in `lambda' - lambda-list expected: (lambda (given (surname "Smith")) (string-append "Hello, " given " " surname))

Call history:

<syntax>      (define greet (lambda (given (surname "Smith")) (string-append "Hello, " given " " surname)))
<syntax>      (##core#set! greet (lambda (given (surname "Smith")) (string-append "Hello, " given " " surname)))
<syntax>      (lambda (given (surname "Smith")) (string-append "Hello, " given " " surname))    <--
Andrea Ciceri
  • 436
  • 6
  • 16

2 Answers2

6

In plain Scheme, you can use dotted tail notation to obtain a list of additional arguments, and then inspect this list to see whether the extra argument was provided:

(define greet
   (lambda (given . rest)
     (let ((surname (if (pair? rest) (car rest) "Smith")))
       (string-append "Hello, " given " " surname))))

Because this is not very convenient, different Scheme systems offer different alternatives for this. In CHICKEN, we support DSSSL annotations, so you can do this:

 (define greet
   (lambda (given #!optional (surname "Smith"))
     (string-append "Hello, " given " " surname)))
sjamaan
  • 2,282
  • 10
  • 19
3

The syntax for optional arguments in Racket is in fact non-standard, so don't expect other interpreters to implement it. In Scheme, the standard features are those defined in the RxRS Scheme reports, with R7RS being the latest one. But fear not - in Chicken Scheme, you can use optional:

[syntax] (optional ARGS DEFAULT)

Use this form for procedures that take a single optional argument. If ARGS is the empty list DEFAULT is evaluated and returned, otherwise the first element of the list ARGS. It is an error if ARGS contains more than one value.

Use it like this:

(define (greet given . surname)
  (string-append "Hello, " given " " (optional surname "Smith")))
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • It's not "standard" in the sense of not being specified in RnRS, but it's actually compatible with [SRFI 89](http://srfi.schemers.org/srfi-89/srfi-89.html), which is standard enough for my taste, and in any event more standard than, say, Guile's style for optional arguments (which is partly based on DSSSL's syntax for optional arguments, as mentioned in sjamaan's answer). – C. K. Young Jul 10 '16 at 19:51