功能的组成
我需要编写一些函数 NTimesComposition(f:(int * int -> int), n:int) ,它接收一些函数 f 和整数 n 并在进行组合之后f,n 次,就像这样 f(x,(f(x,f(x,y)))) <- (这里例如 n = 3 )我开始在 smlnj 上写它,但它似乎比我想象的更复杂,提前感谢您的任何想法:
NTimesComposition(f:(int * int -> int), n:int)
if n = 1 then fn(x,y) => f(x, y ) else NTimesComposition...//here I'm stuck, must be recurstion
I need to write some function NTimesComposition(f:(int * int -> int), n:int) which receives some function f and integer n and after doing composition of f, n times, like this f(x,(f(x,f(x,y)))) <- (here for example n = 3) I began to write it on smlnj, but it seems more complicated than I thought thanks in advance for any idea:
NTimesComposition(f:(int * int -> int), n:int)
if n = 1 then fn(x,y) => f(x, y ) else NTimesComposition...//here I'm stuck, must be recurstion
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您已经获得了 n = 1 的结果,并且您很可能只是忘记在 n > 的递归调用中传递
(x, y)
。 1. 显然这里它需要采用fn (x,y) => 的形式f (x, ...)
其中...
部分是递归调用的位置。如果您忘记了递归部分中的
(x,y)
,则将其设为fn (x,y) =>; NTimesComposition (f, n-1)
那么你最终会构建一个匿名函数链,正如你的参数n
所描述的那样“长”。这将导致您的NTimesComposition
函数的类型不同,具体取决于您提供的n
内容,而由于 SML 类型系统的工作方式,该函数无效 (Hindley-Milner)。以下两个函数将为您完成这项工作
,
其中第一个函数与使用匿名函数的代码最相似。
You already got it for n = 1 and you most likely just forgot to pass the
(x, y)
in the recursive call for n > 1. Obviously here it needs to be something of the formfn (x,y) => f (x, ...)
where the...
part is where your recursive calls is going to be.If you had forgot the
(x,y)
in the recursive part making itfn (x,y) => NTimesComposition (f, n-1)
then you would end up building a chain of anonymous functions as "long" as your argumentn
describes. That would result in a different type of yourNTimesComposition
function depending on whatn
you supply which is not valid due to the way SML's type system works (Hindley-Milner).The following two functions will do the job for you
and
where the first resembles your code the most using the anonymous function.