Advertisement
cwchen

[Go] Higher-order function: partition

Nov 15th, 2017
553
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.61 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "log"
  5. )
  6.  
  7. func partition(arr []int, predicate func(int) bool) ([]int, []int) {
  8.     fit := make([]int, 0)
  9.     nonfit := make([]int, 0)
  10.  
  11.     for _, e := range arr {
  12.         if predicate(e) {
  13.             fit = append(fit, e)
  14.         } else {
  15.             nonfit = append(nonfit, e)
  16.         }
  17.     }
  18.  
  19.     return fit, nonfit
  20. }
  21.  
  22. // eq declared as before.
  23.  
  24. func main() {
  25.     arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
  26.  
  27.     even, odd := partition(arr, func(n int) bool { return n%2 == 0 })
  28.  
  29.     if !eq(even, []int{2, 4, 6, 8, 10}) {
  30.         log.Fatal("Wrong value")
  31.     }
  32.  
  33.     if !eq(odd, []int{1, 3, 5, 7, 9}) {
  34.         log.Fatal("Wrong value")
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement