Home > OS >  Recursive Function Type Defintions
Recursive Function Type Defintions

Time:04-09

I'm a little confused at what is going on here with this recursive type definition:

type Func func() (int, int, Func)

Note: I know how to use it via trial and error but I'm very uncertain as to what it(the recursive type definition) is.

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)
}

Can anyone shed some light on what's created in the above recursive type definition?

CodePudding user response:

type Func func() (int, int, Func) is just a function type whose type name is Func. You can treat it as an anonymous function with zero parameter and 3 return value (and the last return value is also a Func type).

When assign some variable to this function type (Func), the variable will be the name of this function. Then you can call the function with variable-name as the fuction name.

In the code above, d, n, f := get_fib(10), d get 10, n get fib(10), fu get func() (int, int, Func) { return get_fib(11) }. Then you can call f() to which will return the result of get_fib(11) directly.

==============================================================

Why the recursive type is needed to create this functionality:

Just my thoughts: get_fib function wants to return three results: x, the input of fib function (type int), the result of fib function (type int), a function to return the function of get_fib(x 1) (type func, not Func now). (So get_fib is also a kind of recursive because it uses get_fib in its return.) As the function (type func, not Func now) returns a get_fib(x 1) whose return types are the same as those of get_fib(x). So function's return types should be int, int, func (func is the third result in get_fib's return which is the function definition itself). So a recursive function type is needed.

In a brief:

  • Output of get_fib is (int, int, customfunc)
  • Output of customfunc is (get_fib) which is (int, int, customfunc) again.
  • So the customfunc's output is (int, int, customfunc) which is a recursive function type
  •  Tags:  
  • go
  • Related