The idiomatic way to implement generators (yield) in Golang for recursive functions

前端 未结 3 1430
难免孤独
难免孤独 2020-12-13 14:37

[ Note: I read Python-style generators in Go, this is not a duplicate of it. ]

In Python / Ruby / JavaScript / ECMAScript 6, generator functions could be written usi

3条回答
  •  情话喂你
    2020-12-13 15:12

    To my mind usually generators are just wrappers around closure internally. Something like this

    package main
    
    import "fmt"
    
    // This function `generator` returns another function, which
    // we define anonymously in the body of `generator`. The
    // returned function _closes over_ the variable `data` to
    // form a closure.
    func generator(data int, permutation func(int) int, bound int) func() (int, bool) {
        return func() (int, bool) {
            data = permutation(data)
            return data, data < bound
        }
    }
    
    // permutation function
    func increment(j int) int {
        j += 1
        return j
    }
    
    func main() {
        // We call `generator`, assigning the result (a function)
        // to `next`. This function value captures its
        // own `data` value, which will be updated each time
        // we call `next`.
        next := generator(1, increment, 7)
        // See the effect of the closure by calling `next`
        // a few times.
        fmt.Println(next())
        fmt.Println(next())
        fmt.Println(next())
        // To confirm that the state is unique to that
        // particular function, create and test a new one.
        for next, generation, ok := generator(11, increment, 17), 0, true; ok; {
            generation, ok = next()
            fmt.Println(generation)
        }
    }
    

    It looks not as elegant as 'for range' but quite clear semantically and syntactically for me. And it works http://play.golang.org/p/fz8xs0RYz9

提交回复
热议问题