Created
June 15, 2024 07:24
-
-
Save tecnologer/f07fc5766797268656d5c3ddd6140b08 to your computer and use it in GitHub Desktop.
Programacion funcional - transform (map)
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" | |
"math" | |
"strconv" | |
"strings" | |
"golang.org/x/text/cases" | |
"golang.org/x/text/language" | |
) | |
func transform[T, U any](data []T, f func(T) U) []U { | |
res := make([]U, 0, len(data)) | |
for _, e := range data { | |
res = append(res, f(e)) | |
} | |
return res | |
} | |
func main() { | |
languages := []string{"go", "java", "php", "perl", "coldfusion"} | |
fmt.Println("Lenguajes: ", languages) | |
languagesUpper := transform(languages, strings.ToUpper) | |
fmt.Println("Lenguajes en mayusculas: ", languagesUpper) | |
languagesCapitalize := transform(languages, cases.Title(language.English).String) | |
fmt.Println("Lenguajes en capitalizados: ", languagesCapitalize) | |
numbers := []float64{1.5, 25.6, 3.3, 4.5, 5.4, 6.0, 7.33, 8.33, 9.98, 10.12} | |
fmt.Println("Numeros: ", numbers) | |
squares := transform(numbers, math.Sqrt) | |
fmt.Println("Numeros al cuadrado: ", squares) | |
intNumber := transform(numbers, func(n float64) int { | |
return int(n) | |
}) | |
fmt.Println("Numeros enteros: ", intNumber) | |
as_strings := transform(intNumber, strconv.Itoa) | |
fmt.Println("Numeros enteros como cadenas: ", as_strings) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment