Last active
July 31, 2023 19:02
-
-
Save DeedleFake/cc6c9adc3c4bb182994286bbe7bc0ac3 to your computer and use it in GitHub Desktop.
A simple attempt at implementing iterators using golang/go#61405.
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.21 |
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" | |
"strconv" | |
) | |
type Iter[T any] func(func(T) bool) bool | |
func I[T any](i Iter[T]) Iter[T] { return i } | |
func (i Iter[T]) Limit(n int) Iter[T] { | |
return func(yield func(T) bool) bool { | |
return i(func(v T) bool { | |
if n <= 0 { | |
return false | |
} | |
n-- | |
return yield(v) | |
}) | |
} | |
} | |
func Map[F, T any](i Iter[F], f func(F) T) Iter[T] { | |
return func(yield func(T) bool) bool { | |
return i(func(v F) bool { | |
return yield(f(v)) | |
}) | |
} | |
} | |
func Reduce[T, R any](i Iter[T], initial R, reducer func(R, T) R) R { | |
for v := range i { | |
initial = reducer(initial, v) | |
} | |
return initial | |
} | |
type Addable interface { | |
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~string | ~complex64 | ~complex128 | |
} | |
func Sum[T Addable](i Iter[T]) (v T) { | |
return Reduce(i, v, func(acc, cur T) T { return acc + cur }) | |
} | |
func Generate(yield func(int) bool) bool { | |
for i := 0; ; i++ { | |
if !yield(i) { | |
return false | |
} | |
} | |
} | |
func main() { | |
iter := I(Generate) | |
iter2 := iter.Limit(5) | |
iter3 := Map(iter2, func(v int) string { return strconv.FormatInt(int64(v), 10) }) | |
fmt.Printf("%#v\n", Sum(iter3)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment