Reputation: 5879
What's wrong with this code?
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
prev := 0
curr := 1
return func() int {
temp := curr
curr := curr + prev
prev := temp
return curr
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
prog.go:13: prev declared and not used
Upvotes: 8
Views: 2437
Reputation: 166569
If you make the changes suggested by Kevin Ballard, then,
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
prev := 0
curr := 1
return func() int {
temp := curr
curr = curr + prev
prev = temp
return curr
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
Output:
1
2
3
5
8
13
21
34
55
89
The output is not the Fibonacci sequence.
For the Fibonacci sequence,
package main
import "fmt"
func fibonacci() func() int {
a, b := 0, 1
return func() (f int) {
f, a, b = a, b, a+b
return
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
Output:
0
1
1
2
3
5
8
13
21
34
Upvotes: 3
Reputation: 185681
You declared a variable named prev
and then never used it.
Specifically, you said prev := temp
. This is creating a new local variable in the current scope named prev
. I assume you meant to just say prev = temp
, which modifies the prev
variable inherited from the surrounding scope. Similarly you probably meant to say curr = curr + prev
on the previous line, instead of using :=
.
Upvotes: 16