递归函数类型定义
Recursive Function Type Defintions
我对这个递归类型定义的情况有点困惑:
type Func func() (int, int, Func)
注意:我通过反复试验知道如何使用它,但我非常不确定它(递归类型定义)是什么。
package main
import "fmt"
func fib(x int) int {
if x == 0 {
return 0
} else if x == 1 {
return 1
} else {
return fib(x-1) + fib(x-2)
}
}
type Func func() (int, int, Func)
func get_fib(x int) (int, int, Func) {
return x, fib(x), func() (int, int, Func) { return get_fib(x + 1) }
}
func main() {
d, n, f := get_fib(10)
d1, n1, f1 := f()
d2, n2, _ := f1()
fmt.Println(d, n)
fmt.Println(d1, n1)
fmt.Println(d2, n2)
}
任何人都可以阐明在上述递归类型定义中创建的内容吗?
类型Func func() (int, int, Func)
只是一个函数类型,其类型名称是Func
。您可以将其视为具有零参数和 3 个 return 值的匿名函数(最后一个 return 值也是 Func 类型)。
当为这个函数类型(Func
)分配一些变量时,变量将是这个函数的名称。然后就可以调用函数名 variable-name 的函数了。
上面的代码中,d, n, f := get_fib(10)
,d得到10
,n得到fib(10)
,fu得到func() (int, int, Func) { return get_fib(11) }
。然后你可以调用 f()
直接 return get_fib(11)
的结果。
============================================= =================
为什么需要递归类型来创建此功能:
只是我的想法:get_fib函数想要return三个结果:x,fib函数的输入(int类型),fib函数的结果(int类型),一个函数到return get_fib(x+1) 的函数(输入 func,现在不是 Func)。 (因此 get_fib 也是一种递归,因为它在其 return 中使用了 get_fib。)作为函数(类型 func,现在不是 Func)returns a get_fib(x+1) 其 return 类型与 get_fib(x) 相同。所以函数的 return 类型应该是 int, int, func
(func 是 get_fib 的 return 中的第三个结果,它是函数定义本身)。所以需要一个递归函数类型。
简而言之:
- get_fib 的输出是 (int, int, customfunc)
- customfunc 的输出是 (get_fib) 即 (int, int, customfunc) 再次.
- 所以 customfunc 的输出是 (int, int, customfunc) 这是一个递归函数类型
我对这个递归类型定义的情况有点困惑:
type Func func() (int, int, Func)
注意:我通过反复试验知道如何使用它,但我非常不确定它(递归类型定义)是什么。
package main
import "fmt"
func fib(x int) int {
if x == 0 {
return 0
} else if x == 1 {
return 1
} else {
return fib(x-1) + fib(x-2)
}
}
type Func func() (int, int, Func)
func get_fib(x int) (int, int, Func) {
return x, fib(x), func() (int, int, Func) { return get_fib(x + 1) }
}
func main() {
d, n, f := get_fib(10)
d1, n1, f1 := f()
d2, n2, _ := f1()
fmt.Println(d, n)
fmt.Println(d1, n1)
fmt.Println(d2, n2)
}
任何人都可以阐明在上述递归类型定义中创建的内容吗?
类型Func func() (int, int, Func)
只是一个函数类型,其类型名称是Func
。您可以将其视为具有零参数和 3 个 return 值的匿名函数(最后一个 return 值也是 Func 类型)。
当为这个函数类型(Func
)分配一些变量时,变量将是这个函数的名称。然后就可以调用函数名 variable-name 的函数了。
上面的代码中,d, n, f := get_fib(10)
,d得到10
,n得到fib(10)
,fu得到func() (int, int, Func) { return get_fib(11) }
。然后你可以调用 f()
直接 return get_fib(11)
的结果。
============================================= =================
为什么需要递归类型来创建此功能:
只是我的想法:get_fib函数想要return三个结果:x,fib函数的输入(int类型),fib函数的结果(int类型),一个函数到return get_fib(x+1) 的函数(输入 func,现在不是 Func)。 (因此 get_fib 也是一种递归,因为它在其 return 中使用了 get_fib。)作为函数(类型 func,现在不是 Func)returns a get_fib(x+1) 其 return 类型与 get_fib(x) 相同。所以函数的 return 类型应该是 int, int, func
(func 是 get_fib 的 return 中的第三个结果,它是函数定义本身)。所以需要一个递归函数类型。
简而言之:
- get_fib 的输出是 (int, int, customfunc)
- customfunc 的输出是 (get_fib) 即 (int, int, customfunc) 再次.
- 所以 customfunc 的输出是 (int, int, customfunc) 这是一个递归函数类型