Distinguish &optional argument with default value from no value

可紊 提交于 2019-12-01 01:40:30

问题


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

The default default value is nil.

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

and the default value can be set arbitrarily

(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?

EDIT: evidently the page I linked explains this.

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

回答1:


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.

For instance:

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.



来源:https://stackoverflow.com/questions/34469459/distinguish-optional-argument-with-default-value-from-no-value

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