是否可以使用关键字参数传递函数

Jua*_*tas 1 ruby lisp common-lisp

嗨,我想在Ruby 2.0.0-p247中实现这个Common Lisp宏:

(defmacro binary-cmp (a b &key (test-func '>))
  `(funcall #',test-func ,a ,b))
Run Code Online (Sandbox Code Playgroud)

一个二进制测试函数,它接受2个参数和1个关键字参数test_func,test_func默认为gtproc.

gt    = -> (a, b) { a > b }
lt    = -> (a, b) { a < b }
equal = -> (a, b) { a == b }

def binary_cmp (a, b, test_func: gt)
  test_func.(a, b)
end
Run Code Online (Sandbox Code Playgroud)

但这不行,因为在binary_cmp外面看不到:gt.

我该怎么做才能做到这一点?可能吗?或者有一种常见的做法吗?非常感谢你.

编辑:

我需要关键字参数的原因是我的参数列表有5个参数,也许用户只需要默认的测试函数(比方说lt),或者有人想使用(gt)作为默认值.

Rai*_*wig 5

这个Lisp代码在某些方面很糟糕:

(defmacro binary-cmp (a b &key (test-func '>))
  `(funcall #',test-func ,a ,b))
Run Code Online (Sandbox Code Playgroud)
  • 它不应该是一个宏.它应该是一个功能.

  • 宏可以写得更简单.

FUNCALL形式是没有必要的,因为它不会增加的功能.由于设计test-func需要是函数名称(FUNCTION#'期望函数名称),我们可以删除FUNCALL#'.在Lisp语法中,列表的第一个元素是函数名.

(defmacro binary-cmp (a b &key (test-func '>))
  `(,test-func ,a ,b))
Run Code Online (Sandbox Code Playgroud)

作为一个功能,它只是:

(defun binary-predicate (a b &key (predicate '>))
  (funcall predicate a b))
Run Code Online (Sandbox Code Playgroud)