// functions4.go
package main
import (
// "fmt"
)
// apply f to every element of seq
func intMap(f func(int) int, seq []int) {
for i := range seq {
seq[i] = f(seq[i])
}
}
func anyMap(f func(interface{}) interface{}, seq []interface{}) {
for i := range seq {
seq[i] = f(seq[i])
}
}
//
// Go does no allow type variables, so it is not possible to write a function
// like this::
//
// func map(f func(T) T, seq []T) { // T is not a type, so not allowed in Go!
// for i := range seq {
// seq[i] = f(seq[i])
// }
// }
//
// This is importantly different than the interface{} version because it
// requires that the type T is the same for the function and the slice.
//
// Languages like C++ and Java allow this, e.g. and it is called **generic
// types**. While this examples, and ones like it, are easy to understand,
// generic types present many tricky and complicated problems, and so the Go
// designers consciously chose note to add generic types to Go. They felt that
// the cost of the extra complexity in the compiler and program was too high
// for its benefits. They chose to keep Go simpler and easier to understand at
// the expense of leaving out a convenient --- but complex --- feature.
//
func main() {
s := []int{1, 2, 3, 4, 5}
fmt.Println(s)
intMap(func(n int) int { return 2 * n }, s)
fmt.Println(s)
intMap(func(n int) int { return n*n - n }, s)
fmt.Println(s)
// The next two lines cause a compiler error ...
// lst := []int{1, 2, 3, 4}
// anyMap(func(x int) int { return 2 * x }, lst) // compiler error
}