"yield" is backwards

157 views
Skip to first unread message

mspre...@gmail.com

unread,
Feb 7, 2024, 10:43:21 AM2/7/24
to golang-nuts
The go language is getting better and better for functional programming, and I am here for it. I have enjoyed using APL, Scheme, Python. I was excited to see https://go.dev/wiki/RangefuncExperiment . However, I am puzzled by the choice to name the function parameter that _receives_ a Seq's values "yield". That func does the _complement_ to "yield", it _receives_ the value. Compare with Python's "yield" statement, which _provides_ the value. Couldn't we call the func parameter that receives a Seq's values something like "receive" or "consume"?

Thanks,
Mike

Axel Wagner

unread,
Feb 7, 2024, 12:15:52 PM2/7/24
to mspre...@gmail.com, golang-nuts
I'm not sure what you mean. The `yield` function does exactly the same as Python's `yield` statement and in fact, that's part of why the name was chosen.

Compare Python:

def vals(a):
    for v in a:
            yield v

for x in vals([1,2,3]):
    print(x)

With Go:

func vals[T any](s []T) iter.Seq[T] {
    return func(yield func(T) bool) {
        for _, v := range s {
            if !yield(v) { return }
        }
    }
}

func main() {
    for v := range vals([]int{1,2,3}) {
        fmt.Println(v)
    }
}

Sure, there is a little bit more ceremony involved, as you need things to be typed and need to return a closure. But ultimately, the generating function (in Go, the closure) calls yield to… yield a value.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/40005721-c187-48bf-b5c4-d66de2263185n%40googlegroups.com.

Marvin Renich

unread,
Feb 7, 2024, 1:18:00 PM2/7/24
to golan...@googlegroups.com
* mspre...@gmail.com <mspre...@gmail.com> [240207 10:43]:
In addition to what Axel said, note that "yield" is just an arbitrary
function argument name; you may name it anything you choose. Try
changing "yield" to "abc" and it will still work.

...Marvin

mspre...@gmail.com

unread,
Feb 7, 2024, 2:05:08 PM2/7/24
to golang-nuts
I see. I was thinking of it from the point of view of the author of this yield/consume function. From that party's perspective, this function expresses the consumption of the value, not its production. But since the new go lang feature will make that not an explicit function, that is not the most germane point of view.

(Yes, I know what Marvin mentioned.)

Thanks,
Mike
Reply all
Reply to author
Forward
0 new messages