Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default or optional parameters in scheme?

Tags:

lisp

scheme

I'm trying to figure out how to how to set default or optional parameters in Scheme.

I've tried (define (func a #!optional b) (+ a b)) but I can't find of a way to check if b is a default parameter, because simply calling (func 1 2) will give the error:

Error: +: number required, but got #("halt") [func, +]

I've also tried (define (func a [b 0]) (+ a b)) but I get the following error:

Error: execute: unbound symbol: "b" [func]

If it helps I'm using BiwaScheme as used in repl.it

like image 268
Carpetfizz Avatar asked Mar 25 '16 02:03

Carpetfizz


2 Answers

This works fine in Racket:

(define (func a (b 0)) ; same as [b 0]
  (+ a b))

For example:

(func 4)
=> 4
(func 3 2)
=> 5

...But it's not standard syntax, it depends on the Scheme interpreter being used. There's syntax for handling a variable number of arguments, it can be used to handle optional arguments with default values, but it won't look as pretty:

(define (func a . b)
  (+ a (if (null? b) 0 (car b))))

How does it work? b is a list of arguments. If it's empty use zero, otherwise use the value of the first element.

like image 82
Óscar López Avatar answered Oct 19 '22 12:10

Óscar López


Check if your Scheme implementation supports SRFI 89: Optional positional and named parameters.

like image 25
Rainer Joswig Avatar answered Oct 19 '22 13:10

Rainer Joswig