Skip to content

Commit

Permalink
fix: map function
Browse files Browse the repository at this point in the history
  • Loading branch information
araujo88 committed Jul 16, 2024
1 parent ae9c0c9 commit f97f1ac
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 10 deletions.
3 changes: 3 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"fmt"
"strings"
"strconv"

"github.com/araujo88/lambda-go/pkg/core"
"github.com/araujo88/lambda-go/pkg/predicate"
Expand All @@ -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 {
Expand All @@ -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)

Expand Down
17 changes: 7 additions & 10 deletions pkg/core/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit f97f1ac

Please sign in to comment.