Distinguish &optional argument with default value from no value

家住魔仙堡 提交于 2019-12-01 04:17:53

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.

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