0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【A Tour of Go】Basics/More types: structs, slices, and maps. /Exercise: Fibonacci closure (26/27)

Posted at

A Tour of Go の Exercise を実施したときのメモ。

  • Go では case に式がかけるのについ癖で else if を使ってしまう。
  • あと、余計な初期化をかいてしまうのも会社員時代の名残り
  • Exercise ではないが、結果は答えと一緒に出力するようにした
exercise-fibonacci-closure.go
package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	count := 0
	n1 := 0
	n2 := 0
	return func() int {
		ret := 0
		if count == 0 {
			ret = 0
			n1 = 0
			n2 = 0
		} else if count == 1 {
			ret = 1
			n1 = 0
			n2 = 1
		} else {
			ret = n1 + n2
			n1 = n2
			n2 = ret
		}
		count++
		return ret
	}
}

func main() {
	f := fibonacci()
	ans := []int {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946}
	for _, v := range ans {
		fmt.Println(f(), v)
	}
}
  • Go 言語っぽくしたつもり
  • 複数の変数代入を n1, n2 = n2, n1 + n2のように記述できるが、慣れないので気持悪い。コンパイラの違いでバグにならないか心配になってしまう。
exercise-fibonacci-closure.go
package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	count := 0
	n1 := 0
	n2 := 1
	return func() int {
		ret := 0
		switch {
		case count == 0:
			ret = 0
		case count == 1:
			ret = 1
		default:
			n1, n2 = n2, n1 + n2
			ret = n2
		}
		count++
		return ret
	}
}

func main() {
	f := fibonacci()
	ans := []int {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946}
	for _, v := range ans {
		fmt.Println(f(), v)
	}
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?