Apply a callback to an array: Difference between revisions
→{{header|Go}}: replace with Ruby translation
(→{{header|TXR}}: Eliminate call and vecref with [] notation.) |
(→{{header|Go}}: replace with Ruby translation) |
||
Line 686:
=={{header|Go}}==
{{trans|Ruby}}
The task was originally written with a Ruby example, so here are Go versions of the current Ruby examples.
Perhaps in contrast to Ruby, it is idiomatic in Go to use the for statement:
<lang go>package main
import "fmt"
func main() {
func applyCallback(a []int, f func(int) int) {▼
for
}
}</lang>
Alternatively though, an array-like type can be defined and callback-style methods can be defined on it to apply a function to the elements.
<lang go>package main
import "fmt"
type intSlice []int
for _, i := range s {
f(i)
}
}
func
r := make(intSlice, len(s))
return n+1▼
for j, i := range s {
r[j] = f(i)
}
}
func main() {
fmt.Println(i * i)
})
fmt.Println(s.Map(func(i int) int {
return i * i
}))
}</lang>
{{out}}
<pre>
1
4
9
16
25
[1 4 9 16 25]
</pre>
=={{header|Groovy}}==
|