星期二, 2月 06, 2018

Golang Fibonacci Closure


A Tour of Go玩到Fibonacci closure exercise
被前一個範例影響,一直在想把值保留著
但fibonacci是前兩個項目值相加,所以累加沒用,也沒辦法再減前一項的值
想了好久,瞄了解答才瞭解要用「暫存值」

有了"提示"就比較好寫了 XD
package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
    n := 0
    sum := 0
    x := 0
    y := 0
    return func() int{
        if n <= 1 {
            sum = n
        } else {
            sum = x + y
        }
        x = y 
        y = sum
        n++
        return sum
    }
}

func main() {
    f := fibonacci()
    for i := 0; i < 10; i++ {
        fmt.Println(f())
    }
}

解答的下方還有人回更簡單的回覆
真是太強了...

func fibonacci() func() int {
    x, y := 0, 1
    return func() int {
        x, y = y, x+y
        return y - x
    }
}
p.s 話說這個swap的寫法真方便


Reference
Exercise: Fibonacci closure
An answer of the exercise: Fibonacci closure on a tour of Go