From f97f1acd8d95ebe8b0a543862d03eaf6558f8b07 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo Date: Tue, 16 Jul 2024 12:49:21 -0300 Subject: [PATCH] fix: map function --- cmd/main.go | 3 +++ pkg/core/core.go | 17 +++++++---------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 656c888..10f4bf1 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -3,6 +3,7 @@ package main import ( "fmt" "strings" + "strconv" "github.com/araujo88/lambda-go/pkg/core" "github.com/araujo88/lambda-go/pkg/predicate" @@ -14,6 +15,7 @@ func main() { // Example: Doubling the values in a slice of integers intSlice := []int{1, 2, 3, 4, 5} doubled := core.Map(intSlice, func(x int) int { return x * 2 }) + stringNumbers := core.Map(intSlice, strconv.Itoa) sum := core.Foldr(func(x int, acc int) int { return x + acc }, 0, intSlice) greaterThan2 := predicate.Filter(intSlice, func(x int) bool { if x > 2 { @@ -26,6 +28,7 @@ func main() { fmt.Println("Head:", utils.Head(intSlice)) fmt.Println("Tail:", utils.Tail(intSlice)) fmt.Println("Doubled Integers:", doubled) + fmt.Println(stringNumbers) fmt.Println("Sum of integers:", sum) fmt.Println("Filtering elements greater than 2:", greaterThan2) diff --git a/pkg/core/core.go b/pkg/core/core.go index 34f98b9..c734d17 100644 --- a/pkg/core/core.go +++ b/pkg/core/core.go @@ -2,16 +2,13 @@ package core import "golang.org/x/exp/constraints" -// mapSlice applies a function to each element of a slice of type T and returns a new slice of the same type T. -func Map[T any](slice []T, function func(T) T) []T { - newSlice := make([]T, len(slice)) - if len(slice) == 0 { - return []T{} - } - for i, v := range slice { - newSlice[i] = function(v) - } - return newSlice +// mapSlice applies a function to each element of a slice of type T and returns a new slice of type U. +func Map[T any, U any](slice []T, function func(T) U) []U { + newSlice := make([]U, len(slice)) + for i, v := range slice { + newSlice[i] = function(v) + } + return newSlice } // Foldr recursively folds a slice from the right using a function and an initial accumulator value.