daily pastebin goal
5%
SHARE
TWEET

[Go] Higher-order function: filter.

cwchen Nov 15th, 2017 344 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 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. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top