Advertisement
cwchen

[Go] Higher-order function: apply

Nov 15th, 2017
555
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.44 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "log"
  5. )
  6.  
  7. // map is predefined word in Go. Use apply instead.
  8. func apply(arr []int, mapper func(int) int) []int {
  9.     out := make([]int, len(arr))
  10.  
  11.     for i, e := range arr {
  12.         out[i] = mapper(e)
  13.     }
  14.  
  15.     return out
  16. }
  17.  
  18. // eq declared as before.
  19.  
  20. func main() {
  21.     arr := []int{1, 2, 3, 4, 5}
  22.  
  23.     out := apply(arr, func(n int) int { return n * n })
  24.  
  25.     if !eq(out, []int{1, 4, 9, 16, 25}) {
  26.         log.Fatal("Wrong value")
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement