https://github.com/tmr232/go-explore
My explorations of Go
https://github.com/tmr232/go-explore
experimental go golang itertools python
Last synced: about 1 month ago
JSON representation
My explorations of Go
- Host: GitHub
- URL: https://github.com/tmr232/go-explore
- Owner: tmr232
- Created: 2021-12-30T17:40:39.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2022-01-28T15:00:33.000Z (over 4 years ago)
- Last Synced: 2026-02-18T04:37:41.461Z (4 months ago)
- Topics: experimental, go, golang, itertools, python
- Language: Go
- Homepage:
- Size: 59.6 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# go-explore
In this repo I experiment with Golang.
While the packages within may be in a usable state,
they are still highly experimental and subject to change.
## Itertools
Porting Python's `itertools` module (and a bit more) into Go.
It is built around the `Iterator[T]` interface:
```go
type Iterator[T any] interface {
// Next tries to advance to the next value.
// Returns true if a value exists, false if not.
// Once an iterator returns false to indicate exhaustion,
// it should continue returning false.
Next() bool
// Value returns the current value of the iterator.
// Next() must be called and return true before every call to Value().
Value() T
}
```
Iteration is fairly straightforward:
```go
for iter := Literal(1,2,3); iter.Next(); {
fmt.Println(iter.Value())
}
```
Would result in
```text
1
2
3
```
#### Fibonacci
A simple Fibonacci iterator can be written as follows (`itertools.` remove for brevity):
```go
func Fibonacci() Iterator[int] {
a, b := 1, 1
advance := func() (bool, int) {
retval := a
a, b = b, a + b
return true, retval
}
return FromAdvance(advance)
}
```
Note that this iterator is "infinite".
It does not stop after a set number, but keeps going.
If we only want to print the first 10 elements,
we can `Take` the first 10 elements and print them:
```go
ForEach(
Take( // Take the first
10, // 10 elements
Fibonacci(), // from our Fibonacci sequence
),
func(v int) { fmt.Println(v) }, // and print them
)
```
Resulting in
```text
1
1
2
3
5
8
13
21
34
55
```