如何为同一函数提供可选参数和关键字参数? [英] How can I have optional arguments AND keyword arguments to the same function?

查看:98
本文介绍了如何为同一函数提供可选参数和关键字参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个Lisp函数,该函数可以接受可选参数和关键字参数.该功能开始

I am trying to write a Lisp function that can take optional and keyword arguments. The function begins

(defun max-min (v &optional max min &keyword (start 0) (end nil))

当我尝试使用关键字参数而不是可选参数调用函数时,出现错误.我想做的是

When I try to call the function using the keyword arguments but not the optional ones, I get an error. What I'm trying to do is

(max-min #(1 2 3 4) :start 1 :end 2)

我收到错误Error: :START' is not of the expected type REAL'

我认为这是因为它试图将:start绑定到max.我怎样才能使它正常工作?谢谢.

I assume that this is because it is trying to bind :start to max. How can I get this to work? Thanks.

推荐答案

您需要使用必需的参数,可选参数以及关键字参数来调用该函数.否则应该如何工作?您的呼叫缺少可选参数.如果要在调用中指定关键字参数,则可选选项不再是可选的.

You need to call that function with the required parameter, the optional parameters and then the keyword parameters. How should it work otherwise? Your call lacks the optional parameters. If you want to specify keyword parameters in the call, the optional are no longer optional.

(max-min #(1 2 3 4) 0 100 :start 1 :end 2)

基本样式规则:

请勿在函数中将可选参数与关键字参数混合使用.例如,Common Lisp在某个地方使用它,并且它是错误的来源.

Don't mix optional with keyword parameters in a function. Common Lisp for example uses it in some place and it is a source of bugs.

CL:READ-FROM-STRING就是这样的例子.

read-from-string string
                 &optional eof-error-p eof-value
                 &key start end preserve-whitespace

http://www.lispworks.com/documentation/HyperSpec/Body/f_rd_fro.htm

这有效:

(read-from-string " 1 3 5" t nil :start 2)

这也可能起作用:

(read-from-string " 1 3 5" :start 2)

但是用户忘记指定EOF-ERROR-P和EOF-VALUE. Lisp编译器可能不会抱怨,用户会想知道为什么它不会从2开始.

But the user forgot to specify the EOF-ERROR-P and EOF-VALUE. The Lisp compiler may not complain and the user will wonder why it won't start at 2.

这篇关于如何为同一函数提供可选参数和关键字参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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