How to set default or optional parameters in scheme?

*爱你&永不变心* 提交于 2019-12-05 10:31:57

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.

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

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