Tuesday, December 01, 2015

Go语言 斐波那契数列 Exercise: Fibonacci closure

My code:

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
 var ln_prev, ln_current, ln_next int
 ln_current = 1
 return func() int {
  ln_next = ln_current + ln_prev
  ln_prev = ln_current
  ln_current = ln_next
  fmt.Println("log:", ln_prev, ln_current, ln_next)
  return ln_next
 }
}

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


Output:

log: 1 1 1
0 1
log: 1 2 2
1 2
log: 2 3 3
2 3
log: 3 5 5
3 5
log: 5 8 8
4 8
log: 8 13 13
5 13
log: 13 21 21
6 21
log: 21 34 34
7 34
log: 34 55 55
8 55
log: 55 89 89
9 89

Program exited.

Option 2, Learned from Python way :

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
 var la_f []int
 la_f = make([]int, 2)
 la_f = []int{0, 1}
 //la_f := []int{0, 1}
 var li_idx int
 li_idx = 1
 return func() int {
  la_f = append(la_f, la_f[li_idx]+la_f[li_idx-1])
  li_idx = li_idx + 1
  fmt.Printf("log: i %d, value %d, pre element %d \n", li_idx, la_f[li_idx], la_f[li_idx-1])
  return la_f[li_idx]
 }
}

func main() {
 f := fibonacci()
 for i := 0; i < 10; i++ {
  fmt.Printf("idx: %d, value: %d \n", i, f())
 }
}


Output:

log: i 2, value 1, pre element 1
idx: 0, value: 1
log: i 3, value 2, pre element 1
idx: 1, value: 2
log: i 4, value 3, pre element 2
idx: 2, value: 3
log: i 5, value 5, pre element 3
idx: 3, value: 5
log: i 6, value 8, pre element 5
idx: 4, value: 8
log: i 7, value 13, pre element 8
idx: 5, value: 13
log: i 8, value 21, pre element 13
idx: 6, value: 21
log: i 9, value 34, pre element 21
idx: 7, value: 34
log: i 10, value 55, pre element 34
idx: 8, value: 55
log: i 11, value 89, pre element 55
idx: 9, value: 89


Program exited.

 
Reference:
 
 
 

No comments: