Search code examples
functionlambdaargumentsschemechicken-scheme

Default argument in scheme lambda function?


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))    <--

Solution

  • 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)))