在Scheme中对函数进行n次咖喱 [英] Currying a function n times in Scheme
本文介绍了在Scheme中对函数进行n次咖喱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法找出一种方法来咖喱函数指定次数.也就是说,我给该函数一个自然数n和一个有趣的函数,并且该函数将n次咖喱化.例如:
I'm having trouble figuring out a way to curry a function a specified number of times. That is, I give the function a natural number n and a function fun, and it curries the function n times. For example:
(curry n fun)
该函数是可能的应用程序吗?
Is the function and a possible application would be:
(((((curry 4 +) 1) 2) 3) 4)
哪个会产生10.
我真的不确定如何正确实施它.有人可以帮我吗?谢谢:)
I'm really not sure how to implement it properly. Could someone please give me a hand? Thanks :)
推荐答案
;;; no curry
;;; (Int, Int, Int) => Int
(define sum
(lambda (x y z)
(+ x y z) ) )
(sum 1 2 3)
;;; curry once
;;; (Int) => ((Int x Int) => Int)
(define sum
(lambda (x)
(lambda (y z)
(+ x y z) ) ) )
(define sum+10 (sum 10))
(sum+10 10 20)
;;; curry 2 times
;;; (Int) => (Int => (Int => Int) )
(define sum
(lambda (x)
(lambda (y)
(lambda (z)
(+ x y z) ) ) ) )
(define sum+10+20 ((sum 10) 20))
(sum+10+20 30)
;;;现在,我们将从这些示例开始进行概括:
;;; Now we will generalize, starting from these examples:
(define (curry n f)
(if (= n 0)
(lambda (x) x)
(lambda (x) (f ((curry (- n 1) f) x)))))
;;;示例:将函数1+
的11倍应用于初始数字10,结果21:
;;;Example: apply 11 times the function 1+
on the initial number 10 , results 21:
((curry 11 (lambda (x) (+ x 1))) 10)
这篇关于在Scheme中对函数进行n次咖喱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文