Last active
August 24, 2023 04:13
-
-
Save DeedleFake/c5047ec8b12851e3be9d6e6ab6bf1d6d to your computer and use it in GitHub Desktop.
More iterator and pipe operator experimentation.
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 Slice[T any, S ~[]T](s S) Seq[T] { | |
return func(yield func(T) bool) { | |
for _, v := range s { | |
if !yield(v) { | |
return | |
} | |
} | |
} | |
} | |
func Map[T1, T2 any](seq Seq[T1], f func(T1) T2) Seq[T2] { | |
return func(yield func(T2) bool) { | |
seq(func(v T1) bool { | |
return yield(f(v)) | |
}) | |
} | |
} | |
func Filter[T any](seq Seq[T], f func(T) bool) Seq[T] { | |
return func(yield func(T) bool) { | |
seq(func(v T) bool { | |
if !f(v) { | |
return true | |
} | |
return yield(v) | |
}) | |
} | |
} | |
func Windows[T any](seq Seq[T], n int) Seq[[]T] { | |
win := make([]T, 0, n) | |
return func(yield func([]T) bool) { | |
var state func(T) bool | |
full := func(v T) bool { | |
copy(win, win[1:]) | |
win[len(win)-1] = v | |
return yield(win) | |
} | |
fill := func(v T) bool { | |
win = append(win, v) | |
if len(win) == n { | |
state = full | |
return yield(win) | |
} | |
return true | |
} | |
state = fill | |
seq(func(v T) bool { return state(v) }) | |
if len(win) < n { | |
yield(win) | |
} | |
} | |
} | |
func Collect[T any](seq Seq[T]) []T { | |
var r []T | |
seq(func(v T) bool { | |
r = append(r, v) | |
return true | |
}) | |
return r | |
} | |
func Find[T any](seq Seq[T], f func(T) bool) T { | |
var r T | |
seq(func(v T) bool { | |
if f(v) { | |
r = v | |
return false | |
} | |
return true | |
}) | |
return r | |
} | |
func Sum(seq Seq[int]) int { | |
var total int | |
seq(func(v int) bool { | |
total += v | |
return true | |
}) | |
return total | |
} | |
func main() { | |
Generate() |> | |
Windows(10) |> | |
Find(func(v []int) bool { return (Slice(v) |> Sum()) > 100 }) |> | |
fmt.Println() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment