Search code examples
gogenerator

pythons enumerate in go


let's say that I have generator of fibonachi numbers, and I would like to use enumerate(get_next_fibs(10)) and I would like to have generator of pairs index, number_from_generator, I am struggling to find solution with "named return values"

and it's not how it should be done but it's for purpose of learning specific things about generators


package main

import "fmt"

func get_next_fibs(ii int) func() int {
    i := 0
    a, b := 0, 1
    fc := func() int {
        i++
        a, b = b, a+b
        if ii <= i {
            return -1
        }
        return a
    }
    return fc
}

func enumerate(iter func() int) func() (index, v int) {
    index := 0
    fc := func() (index, v int) {
        v := iter()
        return
        index++
    }
    return fc
}

func main() {
    iter := enumerate(get_next_fibs(10))
    // iter := get_next_fibs(10)
    fmt.Printf("iter = %T\n", iter)
    for tuple := iter(); tuple != -1; tuple = iter() {
        fmt.Println("tuple:", tuple)
    }
}

Solution

  • You have few issues in this code sample:

    1. You can't have index++ after return statement. Use defer if you need to do something after return-ing.
    2. You're missing how variable shadowing works in go. Thus, you're trying to modify a wrong index variable.
    3. Go doesn't have tuples.
    ...
    func enumerate(iter func() int) func() (index, v int) {
        counter := 0
        return func() (index, v int) {
            i := counter
            counter++
            return i, iter()
        }
    }
    ...
    func main() {
        iter := enumerate(get_next_fibs(10))
        fmt.Printf("iter = %T\n", iter)
        for i, v := iter(); v != -1; i, v = iter() {
            fmt.Printf("i: %d, v: %d\n", i, v)
        }
    }
    

    Playground link