下面是问题所在:
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/