将默认值与无值区分开&可选参数 [英] Distinguish &optional argument with default value from no value

查看:81
本文介绍了将默认值与无值区分开&可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据GigaMonkeys上的功能,Common Lisp通过&optional支持可选的位置参数.并且默认值可以任意设置.

According to Functions on GigaMonkeys, Common Lisp supports optional positional parameters via &optional and the default value can be set arbitrarily.

默认默认值为nil.

(defun function (mandatory-argument &optional optional-argument) ... )

,默认值可以任意设置

(defun function (mandatory-argument &optional (optional-argument "")) ....)

是否可以区分可选参数具有显式传递的默认值与根本没有值的情况?

Is there a way of distinguishing the cases where the optional parameter has the default value explicitly passed in vs no value at all?

很明显,我链接的页面对此进行了解释.

evidently the page I linked explains this.

有时,了解可选参数的值是否有用 参数由调用方提供或为默认值.相当 而不是编写代码来检查参数的值是否为 默认值(如果调用者碰巧会 明确传递默认值),则可以添加另一个变量名 默认值表达式之后的参数说明符.这 如果调用者实际提供了一个 该参数的参数,否则为NIL.按照惯例,这些 变量通常使用与实际参数相同的名称命名,并带有 最后是"-supplied -p".例如:

Occasionally, it's useful to know whether the value of an optional argument was supplied by the caller or is the default value. Rather than writing code to check whether the value of the parameter is the default (which doesn't work anyway, if the caller happens to explicitly pass the default value), you can add another variable name to the parameter specifier after the default-value expression. This variable will be bound to true if the caller actually supplied an argument for this parameter and NIL otherwise. By convention, these variables are usually named the same as the actual parameter with a "-supplied-p" on the end. For example:

(defun foo (a b &optional (c 3 c-supplied-p)) 
    (list a b c c-supplied-p))

推荐答案

根据规范,您可以在可选参数后添加另一个变量名.如果指定了可选参数,则此变量将绑定到t,否则将绑定到nil.

According to the specification, you can add another variable name after the optional argument. This variable will be bound to t if the optional parameter is specified, and nil otherwise.

例如:

CL-USER> (defun foo (mandatory &optional (optional1 nil optional1-supplied-p))
           (if optional1-supplied-p
               optional1
               mandatory))

FOO
CL-USER> (foo 3 4)
4
CL-USER> (foo 3)
3
CL-USER> (foo 3 nil)
NIL

在第一种情况下,指定了可选参数,以便将其作为函数的结果产生.

In the first case the optional parameter is specified, so that it is produced as result of the function.

在第二种情况下,未指定可选参数,结果是第一个参数.

In the second case the optional parameter is not specified, and the result is the first parameter.

在最后一种情况下,即使可选参数的值等于默认值,该函数也可以区分出实际上已经指定了参数,并可以返回该值.

In the last case, even if the value of the optional parameter is equal to the default value, the function can distinguish that a parameter has actually been specified, and can return that value.

这篇关于将默认值与无值区分开&可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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