Created
December 12, 2013 23:15
-
-
Save thomaswhitcomb/7937271 to your computer and use it in GitHub Desktop.
Functional play time
This file contains 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" | |
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)) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
GO without loops