是否可以对 Lisp 家族语言实现自动柯里化? [英] Is it possible to implement auto-currying to the Lisp-family languages?

查看:20
本文介绍了是否可以对 Lisp 家族语言实现自动柯里化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也就是说,当您仅使用一个参数调用具有 >1 元数的函数时,它应该不显示错误,而是将该参数柯里化并返回具有减少的元数的结果函数.使用 Lisp 的宏可以做到这一点吗?

That is, when you call a function with >1 arity with only one argument, it should, instead of displaying an error, curry that argument and return the resulting function with decreased arity. Is this possible to do using Lisp's macros?

推荐答案

在 Scheme 中,可以使用 curry 过程对函数进行柯里化:

In Scheme it's possible to curry a function using the curry procedure:

(define (add x y)
  (+ x y))

(add 1 2)           ; non-curried procedure call
(curry add)         ; curried procedure, expects two arguments
((curry add) 1)     ; curried procedure, expects one argument
(((curry add) 1) 2) ; curried procedure call

来自 Racket 的文档:

From Racket's documentation:

[curry] 返回一个过程,它是 proc 的柯里化版本.当结果过程第一次被应用时,除非给出它可以接受的最大参数数,否则结果是一个接受额外参数的过程.

[curry] returns a procedure that is a curried version of proc. When the resulting procedure is first applied, unless it is given the maximum number of arguments that it can accept, the result is a procedure to accept additional arguments.

您可以轻松实现一个宏,该宏在定义新过程时自动使用 curry,如下所示:

You could easily implement a macro which automatically uses curry when defining new procedures, something like this:

(define-syntax define-curried
    (syntax-rules ()
      ((_ (f . a) body ...)
       (define f (curry (lambda a (begin body ...)))))))

现在将柯里化add的以下定义:

Now the following definition of add will be curried:

(define-curried (add a b)
  (+ a b))

add
> #<procedure:curried>

(add 1)
> #<procedure:curried>

((add 1) 2)
> 3

(add 1 2)
> 3

这篇关于是否可以对 Lisp 家族语言实现自动柯里化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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