Advertisement
cwchen

[Go] Higher-order function: filter.

Nov 15th, 2017
510
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.59 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "log"
  5. )
  6.  
  7. func filter(arr []int, predicate func(int) bool) []int {
  8.     out := make([]int, 0)
  9.  
  10.     for _, e := range arr {
  11.         if predicate(e) {
  12.             out = append(out, e)
  13.         }
  14.     }
  15.  
  16.     return out
  17. }
  18.  
  19. func eq(m []int, n []int) bool {
  20.     if len(m) != len(n) {
  21.         return false
  22.     }
  23.  
  24.     for i := 0; i < len(m); i++ {
  25.         if m[i] != n[i] {
  26.             return false
  27.         }
  28.     }
  29.  
  30.     return true
  31. }
  32.  
  33. func main() {
  34.     arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
  35.  
  36.     out := filter(arr, func(n int) bool { return n%2 == 0 })
  37.  
  38.     if !eq(out, []int{2, 4, 6, 8, 10}) {
  39.         log.Fatal("Wrong value")
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement