user

// Generic Functions in Go
package main

import "fmt"

func squareSlice[T any, M any](a []T, f func(T) M) []M {
n := make([]M, len(a))
for i, e := range a {
n[i] = f(e)
}
return n
}

func main() {

numbers := []int{1, 2, 3, 4, 5}
squaresInts := squareSlice(numbers, squareInt[int])

// input in `int` format
fmt.Println("numbers = ", numbers)
// output in `int` format
fmt.Println("squaresInts = ", squaresInts)

floats := []float64{1.9, 2.6, 3.4, 4.2, 5.1}
squaresFloats := squareSlice(floats, squareFloat[float64])

// input in `float64` format
fmt.Println("floats = ", floats)
// output in `float64` format
fmt.Println("squaresFloats = ", squaresFloats)

}

// The `squareInt` function returns the square of an integer.
func squareInt[T int](x T) T {
return x * x
}

// The `squareFloat` function returns the square of an integer.
func squareFloat[T float64](x T) T {
return T(int(x) * int(x))
}



user

// Generic Structs in Go
package main

import "fmt"

type Family[U any] struct {
val U
}

func (f Family[U]) setValue(it U) Family[U] {
f.val = it
return f
}

func main() {

fString := Family[string]{}
fString = fString.setValue("Anshuman")

fmt.Println(fString)

fInt := Family[int]{}
fInt = fInt.setValue(56)

fmt.Println(fInt)
}



user

// Functors Pattern in Go
package main

import "fmt"

// The `IntSlice` type represents a functor that maps over a slice of integers.
type IntSlice struct {
slice []int
}

// The `Map` method applies a given function to each element of the slice and returns a new slice with the transformed elements.
func (s IntSlice) Map(f func(int) int) IntSlice {
var result []int
for _, x := range s.slice {
result = append(result, f(x))
}
return IntSlice{result}
}

func main() {
// Define a functor.
numbers := IntSlice{[]int{1, 2, 3, 4, 5}}

squares := numbers.Map(func(x int) int {
return x * x
})

fmt.Println(squares.slice) // Output: [1 4 9 16 25]

squaresSum := squares.Map(func(x int) int {
return x + 1
})

fmt.Println(squaresSum.slice) // Output: [2 8 18 32 50]
}