Last active
November 25, 2022 21:26
-
-
Save debedb/536472650a2033a503667f7502e7ef10 to your computer and use it in GitHub Desktop.
Go: functions as first-class objects, variadic functions and generics
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" | |
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