Advertisement
cwchen

[Go] Higher-order function: enumerate

Nov 15th, 2017
538
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.52 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5. )
  6.  
  7. type Tuple struct {
  8.     Index   int
  9.     Element int
  10. }
  11.  
  12. func enumerate(m []int) func() (Tuple, bool) {
  13.     i := -1
  14.     return func() (Tuple, bool) {
  15.         i += 1
  16.         if i < len(m) {
  17.             return Tuple{Index: i, Element: m[i]}, true
  18.         } else {
  19.             return Tuple{Index: i, Element: 0}, false
  20.         }
  21.     }
  22. }
  23.  
  24. func main() {
  25.     m := []int{10, 20, 30, 40, 50}
  26.  
  27.     iter := enumerate(m)
  28.  
  29.     for {
  30.         out, ok := iter()
  31.         if !ok {
  32.             break
  33.         }
  34.  
  35.         fmt.Println(fmt.Sprintf("%d: %d", out.Index, out.Element))
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement