我有这个curry函数:
(define curry
(lambda (f) (lambda (a) (lambda (b) (f a b)))))我觉得它就像(define curry (f a b))一样。
我的任务是使用curry编写一个函数consElem2All,它的工作方式应该是
(((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进行转换。有谁可以帮我?
提前感谢
bearzk
发布于 2011-07-15 01:05:38
你应该从阅读关于currying的文章开始。如果你不了解curry是怎么回事,可能真的很难使用它……在您的情况下,http://www.engr.uconn.edu/~jeffm/Papers/curry.html可能是一个很好的开始。
currying的一个非常常见和有趣的用法是与reduce或map这样的函数一起使用(对于它们自己或它们的参数)。
让我们定义两个currying运算符!
(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))然后是curried /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)我希望这能帮助你掌握currying的用处...
发布于 2011-06-27 06:57:38
所以你的curry版本有一个带有两个参数的函数,比方说:
(define (cons a b) ...)然后把它变成你可以这样叫的东西:
(define my-cons (curry cons))
((my-cons 'a) '(b c)) ; => (cons 'a '(b c)) => '(a b c)你实际上有一个函数,它需要三个参数。如果你有一个管理3元函数的curry3,你可以这样做:
(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用法,即在cons周围包装一个lambda,以获取传递给cons的元素。如何将x转换为cons,以便获得可直接用于映射的单参数函数?
发布于 2011-06-29 22:18:04
(define (consElem2All0 x lst)
(map ((curry cons) x) lst))https://stackoverflow.com/questions/6487104
复制相似问题