Skip to content

Commit f97f1ac

Browse files
committed
fix: map function
1 parent ae9c0c9 commit f97f1ac

File tree

2 files changed

+10
-10
lines changed

2 files changed

+10
-10
lines changed

cmd/main.go

+3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"fmt"
55
"strings"
6+
"strconv"
67

78
"github.com/araujo88/lambda-go/pkg/core"
89
"github.com/araujo88/lambda-go/pkg/predicate"
@@ -14,6 +15,7 @@ func main() {
1415
// Example: Doubling the values in a slice of integers
1516
intSlice := []int{1, 2, 3, 4, 5}
1617
doubled := core.Map(intSlice, func(x int) int { return x * 2 })
18+
stringNumbers := core.Map(intSlice, strconv.Itoa)
1719
sum := core.Foldr(func(x int, acc int) int { return x + acc }, 0, intSlice)
1820
greaterThan2 := predicate.Filter(intSlice, func(x int) bool {
1921
if x > 2 {
@@ -26,6 +28,7 @@ func main() {
2628
fmt.Println("Head:", utils.Head(intSlice))
2729
fmt.Println("Tail:", utils.Tail(intSlice))
2830
fmt.Println("Doubled Integers:", doubled)
31+
fmt.Println(stringNumbers)
2932
fmt.Println("Sum of integers:", sum)
3033
fmt.Println("Filtering elements greater than 2:", greaterThan2)
3134

pkg/core/core.go

+7-10
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,13 @@ package core
22

33
import "golang.org/x/exp/constraints"
44

5-
// mapSlice applies a function to each element of a slice of type T and returns a new slice of the same type T.
6-
func Map[T any](slice []T, function func(T) T) []T {
7-
newSlice := make([]T, len(slice))
8-
if len(slice) == 0 {
9-
return []T{}
10-
}
11-
for i, v := range slice {
12-
newSlice[i] = function(v)
13-
}
14-
return newSlice
5+
// mapSlice applies a function to each element of a slice of type T and returns a new slice of type U.
6+
func Map[T any, U any](slice []T, function func(T) U) []U {
7+
newSlice := make([]U, len(slice))
8+
for i, v := range slice {
9+
newSlice[i] = function(v)
10+
}
11+
return newSlice
1512
}
1613

1714
// Foldr recursively folds a slice from the right using a function and an initial accumulator value.

0 commit comments

Comments
 (0)