To try this code, you can use the modified Go toolchain found at https://github.com/DeedleFake/go/tree/pipe-operator.
Created
August 22, 2023 22:54
-
-
Save DeedleFake/eaa9b480a1f02b5d716c53e8318b4df2 to your computer and use it in GitHub Desktop.
Go iterators using Elixir pipe operator.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module test | |
go 1.22 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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