7

我有这个curry功能:

(define curry
(lambda (f) (lambda (a) (lambda (b) (f a b)))))

我认为它就像(define curry (f a b))

consElem2All我的任务是使用编写一个函数curry,它应该像

(((consElem2All cons) 'b) '((1) (2 3) (4)))
>((b 1) (b 2 3) (b 4))

我以常规方式编写了此函数:

(define (consElem2All0 x lst) 
  (map (lambda (elem) (cons x elem)) lst))

但仍然不知道如何用curry. 谁能帮我?

提前致谢

熊熊

4

3 回答 3

4

您应该从阅读有关柯里化的内容开始。如果您不了解咖喱是什么,可能真的很难使用它...在您的情况下,http://www.engr.uconn.edu/~jeffm/Papers/curry.html可能是一个不错的选择开始。

currying 的一种非常常见和有趣的用法是使用 reduce 或 map 等函数(对于它们自己或它们的参数)。

让我们定义两个柯里化运算符!

(define curry2 (lambda (f) (lambda (arg1) (lambda (arg2) (f arg1 arg2)))))
(define curry3 (lambda (f) (lambda (arg1) (lambda (arg2) (lambda (arg3) (f arg1 arg2 arg3))))))

然后是一些柯里化的数学函数:

(define mult (curry2 *))
(define double (mult 2))

(define add (curry2 +))
(define increment (add 1))
(define decrement (add -1))

然后是咖喱减少/映射:

(define creduce (curry3 reduce))
(define cmap (curry2 map))

使用它们

首先减少用例:

(define sum ((creduce +) 0))
(sum '(1 2 3 4)) ; => 10

(define product (creduce * 1))
(product '(1 2 3 4)) ; => 24

然后映射用例:

(define doubles (cmap double))
(doubles '(1 2 3 4)) ; => (2 4 6 8)

(define bump (cmap increment))
(bump '(1 2 3 4)) ; => (2 3 4 5)

我希望这可以帮助您掌握currying的用处...

于 2011-07-14T17:05:38.400 回答
1

所以你的 curry 版本需要一个带有两个参数的函数,比如说:

(define (cons a b) ...)

并把它变成你可以这样称呼的东西:

(define my-cons (curry cons))
((my-cons 'a) '(b c)) ; => (cons 'a '(b c)) => '(a b c)

您实际上有一个需要三个参数的函数。如果您有一个curry3托管的 3 元函数,您可以执行以下操作:

(define (consElem2All0 the-conser x lst) ...)

(就像您所做的那样,但允许使用除 cons 之外的类似 cons 的功能!)

然后这样做:

(define consElem2All (curry3 consElem2All0))

你手头没有这样的curry3东西。因此,您可以构建一个,也可以通过自己“手动”柯里化额外变量来解决它。解决它看起来像:

(define (consElem2All0 the-conser)
  (lambda (x lst) ...something using the-conser...))
(define (consElem2All the-conser)
  (curry (consElem2All0 the-conser)))

请注意,在 map 表达式本身中还有另一种可能的 curry 用法,这暗示着您将 lambda 包裹在 cons 周围以将元素传递给 cons。你怎么能curry xinto cons,以便获得一个可以直接用于映射的单参数函数?...

于 2011-06-26T22:57:37.763 回答
-1
(define (consElem2All0 x lst) 
  (map ((curry cons) x) lst))
于 2011-06-29T14:18:04.450 回答