Skip to content

Instantly share code, notes, and snippets.

@debedb
Last active November 25, 2022 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save debedb/536472650a2033a503667f7502e7ef10 to your computer and use it in GitHub Desktop.
Save debedb/536472650a2033a503667f7502e7ef10 to your computer and use it in GitHub Desktop.
Go: functions as first-class objects, variadic functions and generics
package main
import "fmt"
func plus[T int | float32](i1 T, i2 T) T {
return i1 + i2
}
func minus[T int | float32](i1 T, i2 T) T {
return i1 - i2
}
func variade[T int | float32](f func(T, T) T, args ...T) T {
if args == nil {
panic("Not enough arguments")
}
if len(args) == 2 {
return f(args[0], args[1])
}
// This would be wrong, cause subtraction is not associative:
// return f(args[0], variade(f, args[1:]...))
return variade(f, append([]T{f(args[0], args[1])}, args[2:]...)...)
}
func main() {
fmt.Println(float32(variade(minus[int], 100, 90, 9)))
// Prints 7.6
fmt.Println(variade(plus[float32], 1.1, 2.2, 3.3, float32(variade(minus[int], 100, 90, 9))))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment