Last active
August 29, 2015 14:06
-
-
Save svanellewee/aa024ea836e409ed7d3e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /* lessons learnt: | |
| - inside other functions you can't do func bla (); | |
| (use bla := func() ...) | |
| - Too many values usually indicates you didnt specify return values in prototype | |
| */ | |
| type cbfunc func(int,float64); | |
| foreach64 := func (xs []float64, fn func(int, float64)) { | |
| for i,v := range(xs) { | |
| fn(i,v); | |
| } | |
| } | |
| fmt.Println("\nForeach!"); | |
| foreach64(arr, func (index int, val float64) { | |
| fmt.Printf("[%d] --> [%f]\n",index,val); | |
| }) | |
| fmt.Println("\nReduce!"); | |
| reduce64 := func(initval float64, xs []float64, cb func(total float64,index int, val float64) float64) float64 { | |
| totalval := initval; | |
| foreach64(xs,func (idx int, vval float64) { | |
| totalval = cb(totalval, idx, vval); | |
| }) | |
| return totalval | |
| }; | |
| fmt.Printf("result of reduce(%g) = %f\n", arr, reduce64(0,arr, func (total float64, index int, val float64) float64 { | |
| return total + val | |
| }) ) | |
| fmt.Println("\nMap!"); | |
| map64 := func(xs []float64, cb func(index int, val float64) float64) []float64 { | |
| newxs := make([]float64,0) | |
| foreach64(xs, func(idxx int, vval float64) { | |
| newxs = append(newxs, cb(idxx, vval)) | |
| }); | |
| return newxs; | |
| } | |
| fmt.Printf("oldarr[%g] --> newarr[%g]\n", arr, map64(arr, func(index int, val float64) float64 { | |
| return 2* val; | |
| })); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Foreach!
[0] --> [1.000000]
[1] --> [2.000000]
[2] --> [3.000000]
[3] --> [4.000000]
[4] --> [45.000000]
Reduce!
result of reduce([1 2 3 4 45]) = 55.000000
Map!
oldarr[[1 2 3 4 45]] --> newarr[[2 4 6 8 90]]