2
2

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.

無限リスト的な何かをGoで

Posted at

Goで無限リスト(遅延リスト)的なものが欲しくなった。

前提:channelとgoroutineは使わない方針。

クロージャ使うとこんな感じ。

func nums() func() int {
	var n int
	return func() int {
		n++
		return n
	}
}

値と一緒に次の値を返す関数を返すならこんな感じ。

type nums func() (int, nums)

func newNums(n int) nums {
	return func() (int, nums) {
		return n+1, newNums(n+1)
	}
}

前者のほうがシンプルに見えるけど、後者のほうが変に状態を状態を持たなくて良さそう。

struct作ってメソッド生やしてってやるのもいいけど、高階関数と多値返せることを活かしてなるべく純粋に書こうと心がけてる。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?