Created
August 20, 2024 15:10
-
-
Save moniquelive/9cc5dc90bf4c7742d6974605dff1017c to your computer and use it in GitHub Desktop.
Map iterator function in GO
This file contains hidden or 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" | |
"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