如何在方案中设置默认或可选参数? [英] How to set default or optional parameters in scheme?

查看:114
本文介绍了如何在方案中设置默认或可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何在Scheme中设置默认或可选参数.

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

我已经尝试过(define (func a #!optional b) (+ a b)),但是我找不到一种方法来检查b是否为默认参数,因为简单地调用(func 1 2)会产生错误:

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, +]

我也尝试过(define (func a [b 0]) (+ a b)),但出现以下错误:

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

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

如果有帮助,我可以使用 BiwaScheme : //repl.it/languages/scheme"rel =" nofollow> repl.it

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

推荐答案

在球拍中工作正常:

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

例如:

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

...但这不是标准语法,它取决于所使用的Scheme解释器.有用于处理可变数量参数的语法,它可以用于处理具有默认值的可选参数,但是看起来不那么漂亮:

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

它如何工作? 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.

这篇关于如何在方案中设置默认或可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆