#(Fibonacci exercise) Is it possible to name a function and then return the name?

9 messages · Page 1 of 1 (latest)

low tiger
#

Forgive my ignorance! Still working through the Go tour and I came across the Fibonacci exercise.

My initial impression is that the below code matches the Fibonacci function signature.

func fibonacci() func() int {
    first, second := 0, 1
    func next() int {
        ret := first
        first, second = second, first+second
        return ret
    }
    return next
}

But the above function does not compile. I can't help but feel that it is more readable than an unnamed function (like below), and should be in theory equivalent. Am I just doing something wrong that I can't seem to identify yet, or is this actually just a no-no in Go?

func fibonacci() func() int {
    first, second := 0, 1
    return func() int {
        ret := first
        first, second = second, first+second
        return ret
    }
}
tall temple
#

what would happen when you assign the "next" functions to variables with other names?

low tiger
#

I'm not sure I understand, next is just a way to identify for a developer what the inner function is doing; it won't exist outside the scope of fibonacci. (This is my interpretation at this point of my learning journey!)

To elaborate, I expect that calling

f := fibonacci()

fmt.Println(f())
fmt.Println(f())
fmt.Println(f())

To keep yielding the next values.

next is still of type func and it returns an int, so invoking f() is supposed to be invoking next() each call.

static prairie
#
func fibonacci() func() int {
    first, second := 0, 1
    next := func() int {
        ret := first
        first, second = second, first+second
        return ret
    }
    return next
}``` is what Tail meant
#

alternatively go func fibonacci() (next func() int) { first, second := 0, 1 return func() int { ret := first first, second = second, first+second return ret } }

low tiger
static prairie
#

right

#

as to why it is forbidden, I don't personally know

#

in go, these sort of decisions tend to fall into one of 3 buckets:
1 - not needed
2 - not useful enough
3 - has hairy implications