Skip to content

Instantly share code, notes, and snippets.

@DeedleFake
Created August 22, 2023 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DeedleFake/eaa9b480a1f02b5d716c53e8318b4df2 to your computer and use it in GitHub Desktop.
Save DeedleFake/eaa9b480a1f02b5d716c53e8318b4df2 to your computer and use it in GitHub Desktop.
Go iterators using Elixir pipe operator.
module test
go 1.22
package main
import (
"fmt"
)
type Seq[T any] func(func(T) bool)
func Generate() Seq[int] {
return func(yield func(int) bool) {
for i := 0; ; i++ {
if !yield(i) {
return
}
}
}
}
func Limit[T any](s Seq[T], n int) Seq[T] {
return func(yield func(T) bool) {
s(func(v T) bool {
if n <= 0 {
return false
}
n--
return yield(v)
})
}
}
func Filter[T any](s Seq[T], f func(T) bool) Seq[T] {
return func(yield func(T) bool) {
s(func(v T) bool {
if f(v) {
return yield(v)
}
return true
})
}
}
func Map[T1, T2 any](s Seq[T1], f func(T1) T2) Seq[T2] {
return func(yield func(T2) bool) {
s(func(v T1) bool { return yield(f(v)) })
}
}
func Collect[T any](s Seq[T]) []T {
var r []T
s(func(v T) bool {
r = append(r, v)
return true
})
return r
}
func main() {
s := Generate() |>
Filter(func(v int) bool { return v%2 != 0 }) |>
Map(func(v int) int { return v*2 }) |>
Limit(10) |>
Collect()
fmt.Println(s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment