How to set default or optional parameters in scheme?

微笑、不失礼 提交于 2019-12-07 07:32:47

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/36213204/how-to-set-default-or-optional-parameters-in-scheme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!