Search code examples
arraysgoreduce

Array Reduce or similar


I have an array:

const assets = [{
  type: 'X',
  value: 322.12
}, {
  type: 'X',
  value: 413.21
}]

I want the sum of values (735,33)

In node.js I can use: const sum = assets.reduce((s, val) => ( s = s + val.value), 0)

How can I do the same in Go?


Solution

  • Here is an incomplete implementation, but it gives you an idea of why this is a bad idea and non-idiomatic Go:

    package main
    
    import "fmt"
    
    type Array []int
    
    type ReducerFn func(prev int, next int) int
    
    func (arr Array) Reduce(fn ReducerFn, i int) int {
        prev := i
        for _, v := range arr {
            prev = fn(prev, v)
        }
        return prev
    }
    
    func main() {
        i := Array([]int{1,2,4})
        fmt.Println(i.Reduce(func(prev int, next int) int { 
            return prev + next
        }, 10))
    }
    

    Since there are no generics in Go, you'll have to create a different reducer method for every return type, which might be quite impractical.

    See also Francesc Campoy's talk at dotGo2015, "Functional Go?".