daily pastebin goal
36%
SHARE
TWEET

[Go] Higher-order function: enumerate

cwchen Nov 15th, 2017 254 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. }
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