Skip to content

Instantly share code, notes, and snippets.

@thomaswhitcomb
Created December 12, 2013 23:15
Show Gist options
  • Save thomaswhitcomb/7937271 to your computer and use it in GitHub Desktop.
Save thomaswhitcomb/7937271 to your computer and use it in GitHub Desktop.
Functional play time
package main
import "fmt"
type II interface{}
func mapper (collection [] II,fn func(II) II) [] II {
mapped := make([] II,0)
for _,v := range(collection){
mapped = append(mapped,fn(v))
}
return mapped
}
func fold(collection [] II, accum II, fn func(II, II) II) II {
for _,v := range(collection){
accum = fn(v,accum)
}
return accum
}
func main(){
// Test collection of integers
var coll_int = [] II {2,4,3,2,9}
var f_add1 = func(x II) II{
return x.(int) + 1
}
fmt.Println(mapper(coll_int,f_add1))
// Test collection of integers
var coll_string = [] II {"a","b","c","d"}
var f_concat_x = func(x II) II{
return x.(string) + "x"
}
fmt.Println(mapper(coll_string,f_concat_x))
// Fold of an integer collection
var f_sum = func(i II, accum II) II{
return accum.(int) + i.(int)
}
fmt.Println(fold(coll_int,0,f_sum))
}
@thomaswhitcomb
Copy link
Author

GO without loops

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment