使用 Go 语法的函数组合

Function composition using Go syntax

问题如下:

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