Skip to content

Instantly share code, notes, and snippets.

@jakecoffman
Last active December 14, 2021 16:04
Show Gist options
  • Save jakecoffman/1db38b3cf77f549e6b77 to your computer and use it in GitHub Desktop.
Save jakecoffman/1db38b3cf77f549e6b77 to your computer and use it in GitHub Desktop.
Example of functional programming in Golang.
package main
import (
"constraints"
"fmt"
)
func main() {
fmt.Println(Sum(1, 2, 3, 4))
fmt.Println(Sum("1", "2", "3"))
}
func Map[T any](operation func(p T) T, is ...T) []T {
r := make([]T, len(is))
for index, value := range is {
r[index] = operation(value)
}
return r
}
func Reduce[T any](operation func(a, b T) T, is ...T) T {
var r T
for index, value := range is {
if index == 0 {
r = value
} else {
r = operation(r, value)
}
}
return r
}
func Add[T constraints.Ordered](a, b T) T {
return a + b
}
func Sum[T constraints.Ordered](i ...T) T {
return Reduce(Add[T], i...)
}
@jakecoffman
Copy link
Author

It looks like some people are stumbling across this (thanks Google!) so I should mention that using interface causes a performance hit. You're probably better off with a for loop for now.

@jakecoffman
Copy link
Author

Now that generics are here there's less of a performance hit doing functional programming! I've updated the gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment