Skip to content

Instantly share code, notes, and snippets.

@icholy
Last active December 16, 2015 23:59
Show Gist options
  • Save icholy/5517898 to your computer and use it in GitHub Desktop.
Save icholy/5517898 to your computer and use it in GitHub Desktop.
i like to pretend sometimes
type Stream<T> chan T
func (c Stream<T>) Map<U>(f func(T) U) Stream<U> {
out := make(Stream<U>)
go func(){
for x := range c {
out <- f(x)
}
}()
return out
}
func (c Stream<T>) Filter(f func(T) bool) Stream<T> {
out := make(Stream<T>)
go func() {
for x := range c {
if f(x) {
out <- x
}
}
}()
return out
}
func (c Stream<T>) Reduce<U>(f func(U, T) (U, bool)) Stream<U> {
out := make(Stream<U>)
go func() {
var acc U
for x := range c {
if acc, ok := f(acc, x); ok {
out <- acc
}
}
}()
return out
}
func (c Stream<T>) Each(f func(T)) {
go func() {
for x := range c {
go f(x)
}
}
}
func main() {
stream := make(Stream<string>)
results := make(chan string)
stream.Map(func(s string) Stream<int> {
out := make(Stream<int>)
go func() { for i := 0; i < len(string); i++ { out <- i } }()
return out
}).Each(func(s Stream<int>) {
s.Filter(func(x int) bool { return x > 5 })
.Map(func(x int) string { return strconv.Itoa(x) })
.Each(func(s string) { results <- s })
})
for x := results {
println(x)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment