本文介绍了咖喱计划的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 curry 函数:

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

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

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

my assignment is to write a function consElem2All using curry,which should work like

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

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

I have wrote this function in a regular way:

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

但仍然不知道如何用curry 转换它.有人可以帮我吗?

but still don't know how to transform it with curry. Can anyone help me?

提前致谢

熊熊

推荐答案

你应该从阅读柯里化开始.如果你不明白咖喱是什么,它可能真的很难使用......在你的情况下,http://www.engr.uconn.edu/~jeffm/Papers/curry.html 可能是一个好的开始.

You should begin by reading about currying. If you don't understand what curry is about, it may be really hard to use it... In your case, http://www.engr.uconn.edu/~jeffm/Papers/curry.html may be a good start.

柯里化的一个非常常见和有趣的用途是使用 reduce 或 map(用于它们自己或它们的参数)等函数.

One very common and interesting use of currying is with functions like reduce or map (for themselves or their arguments).

(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))))))

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

Then a few curried mathematical functions:

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

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

然后是咖喱的reduce/map:

And then come the curried reduce/map:

(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)

希望能帮助你掌握柯里化的用处...

I hope that helps you grasp the usefulness of currying...

这篇关于咖喱计划的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 15:10