Skip to content

Instantly share code, notes, and snippets.

@svanellewee
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save svanellewee/aa024ea836e409ed7d3e to your computer and use it in GitHub Desktop.

Select an option

Save svanellewee/aa024ea836e409ed7d3e to your computer and use it in GitHub Desktop.
/* 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;
}));
@svanellewee
Copy link
Author

Will only work for float64 arrays. I dont know enough to make these generic...yet.

@svanellewee
Copy link
Author

What about fold left / fold right? I think tail recursion optimization would have been nice for fold right, but since this isn't Haskell or Lua though, maybe basing things on foreach[64] is a safer plan?

@svanellewee
Copy link
Author

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]]

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