Jump to content

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 i_, ei := range a[]int{1, 2, 3, 4, 5} {
a[fmt.Println(i] =* f(ei)
}
}</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
 
func applyCallback(as []int,intSlice) each(f func(int) int) {
for _, i := range s {
f(i)
}
}
 
func inc(ns intSlice) Map(f func(int) int) intSlice {
r := make(intSlice, len(s))
return n+1
for j, i := range s {
r[j] = f(i)
}
return n+1r
}
 
func main() {
as := []intintSlice{31, 12, 3, 4, 5}
 
applyCallback(a, inc)
fmts.Printlneach(afunc(i int) {
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}}==
1,707

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.