Skip to content

Instantly share code, notes, and snippets.

@moniquelive
Created August 20, 2024 15:10
Show Gist options
  • Save moniquelive/9cc5dc90bf4c7742d6974605dff1017c to your computer and use it in GitHub Desktop.
Save moniquelive/9cc5dc90bf4c7742d6974605dff1017c to your computer and use it in GitHub Desktop.
Map iterator function in GO
package main
import (
"fmt"
"iter"
"math"
"strings"
)
// Map : A -> B
func Map[Slice ~[]A, A any, B any](s Slice, f func(A) B) iter.Seq2[int, B] {
return func(yield func(int, B) bool) {
for i, v := range s {
if !yield(i, f(v)) {
return
}
}
}
}
func main() {
for i, v := range Map([]float64{1, 2, 3, 4, 5}, math.IsNaN) {
fmt.Println(i, v)
}
for i, v := range Map([]string{"hello", "world"}, strings.ToUpper) {
fmt.Println(i, v)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment