go - 使用Go语法的函数组合

标签 go recursion currying

下面是问题所在:

Define a function make_fn_repeater which takes in a one-argument function
f and an integer x. It should return another function which takes in one
argument, another integer. This function returns the result of applying f to
x this number of times.
Make sure to use recursion in your solution, as shown below:


func make_fn_repeater(___________________):
    if _______________________:
          return __________________
    else:
          return __________________
    return ____________________

样本输出:
incr_1 := make_func_repeater(lambda x: x + 1, 1)
incr_1(2) // returns 3
incr_1(5) // returns 6

下面的解决方案是没有递归的:
package main

import "fmt"

type fn func(int) int

func makeFnRepeater(f fn, x int) fn {

    return func(y int) int {
        return f(y)
    }

}

func main() {
    inc := makeFnRepeater(func(x int) int { return x + 1 }, 1)
    fmt.Println(inc(2))
    fmt.Println(inc(5))

}

是否可以使用递归来实现解决方案?我没看到

最佳答案

听起来您想这样做:

func makeFnRepeater(f fn, x int) fn {
  if x == 1 {
    return f
  } else {
    return func(y int) int {
      return f(makeFnRepeater(f, x - 1)(y))
    }
  }
}
https://play.golang.org/p/YbiSClzipOK

关于go - 使用Go语法的函数组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63005130/

相关文章:

function - 如何理解这个递归结果

go - 在实例生成期间修改结构字段

go - 从文件中读取字节到内存中

scala - 为什么 Scala 提供多个参数列表和每个列表多个参数?

scala - 无法应用参数化柯里化(Currying)函数

go - 在 Go 中将一个 writer 包装在一个 reader 中?

c++ - 递归删除指定数据的链表

algorithm - 与以 n 表示的变量的递归关系

java - 圣诞树的错误展示

c++ - qt 插槽柯里化(Currying)