Advertisement
cwchen

[Go] Higher-order function: zip

Nov 15th, 2017
529
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.60 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5. )
  6.  
  7. type Tuple struct {
  8.     First  int
  9.     Second int
  10. }
  11.  
  12. func zip(m []int, n []int) func() (Tuple, bool) {
  13.     if len(m) != len(n) {
  14.         panic("Unequal list length")
  15.     }
  16.  
  17.     i := -1
  18.     return func() (Tuple, bool) {
  19.         i += 1
  20.         if i < len(m) {
  21.             return Tuple{First: m[i], Second: n[i]}, true
  22.         } else {
  23.             return Tuple{First: 0, Second: 0}, false
  24.         }
  25.     }
  26. }
  27.  
  28. func main() {
  29.     m := []int{1, 2, 3}
  30.     n := []int{4, 5, 6}
  31.  
  32.     // Get the iterator
  33.     iter := zip(m, n)
  34.  
  35.     // Iterate through the list.
  36.     for {
  37.         out, ok := iter()
  38.         if !ok {
  39.             break
  40.         }
  41.  
  42.         fmt.Println(out)
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement