daily pastebin goal
18%
SHARE
TWEET

[Go] Higher-order function: reduce

cwchen Nov 15th, 2017 153 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "log"
  5. )
  6.  
  7. func reduce(arr []int, reducer func(int, int) int) int {
  8.     if len(arr) == 0 {
  9.         return 0
  10.     } else if len(arr) == 1 {
  11.         return arr[0]
  12.     }
  13.  
  14.     n := arr[0]
  15.  
  16.     for i := 1; i < len(arr); i++ {
  17.         n = reducer(n, arr[i])
  18.     }
  19.  
  20.     return n
  21. }
  22.  
  23. func main() {
  24.     arr := []int{1, 2, 3, 4, 5}
  25.  
  26.     n := reduce(arr, func(a int, b int) int { return a + b })
  27.  
  28.     if !(n == 15) {
  29.         log.Fatal("Wrong value")
  30.     }
  31. }
RAW Paste Data
Top