功能的组成

发布于 2024-10-03 20:20:06 字数 427 浏览 4 评论 0原文

我需要编写一些函数 NTimesComposition(f:(int * int -> int), n:int) ,它接收一些函数 f 和整数 n 并在进行组合之后fn 次,就像这样 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

超可爱的懒熊 2024-10-10 20:20:06

您已经获得了 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)。

以下两个函数将为您完成这项工作

fun foo (f, 1) = (fn xy => f xy)
  | foo (f, n) = (fn (x,y) => f(x, foo (f, n-1) (x,y)))

fun baz (f, 1) xy = f xy
  | baz (f, n) (x,y) = f(x, foo (f, n-1) (x,y))

其中第一个函数与使用匿名函数的代码最相似。

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 form fn (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 it fn (x,y) => NTimesComposition (f, n-1) then you would end up building a chain of anonymous functions as "long" as your argument n describes. That would result in a different type of your NTimesComposition function depending on what n 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

fun foo (f, 1) = (fn xy => f xy)
  | foo (f, n) = (fn (x,y) => f(x, foo (f, n-1) (x,y)))

and

fun baz (f, 1) xy = f xy
  | baz (f, n) (x,y) = f(x, foo (f, n-1) (x,y))

where the first resembles your code the most using the anonymous function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文