Hacker News new | past | comments | ask | show | jobs | submit login

"range-over-functions"

Yes, something people coming to Go would have assumed worked before looking at all range cases, but didn't.




range-over-functions is the experimental new feature where a function can generate a sequence by executing a bit at a time, i.e.

  s := []string{"hello", "world"}
  for i, x := range slices.Backward(s) {
    fmt.Println(i, x)
  }

  func Backward[E any](s []E) func(func(int, E) bool) {
    return func(yield func(int, E) bool) {
        for i := len(s)-1; i >= 0; i-- {
            if !yield(i, s[i]) {
                return
            }
        }
    }
  }
I don't think anyone expects this to work in Go as it is today, it's just a new feature that will make the language more complex, but it will make certain kinds of programs simpler to write.

I should also note that the official name is "range-over-function iterators", I called it by a wrong name earlier.


Yes might depend on where you come from. As someone with decades of Java experience - not a fancy language over most of its lifecycle - I was mystified why there is no Iterator support as in Java for loops.


Oh, now I understand what you mean - you're thinking of this as a way to do `for (T x : collection)` in Java.

I see this as more like the `yield return` functions of C#, which I definitely wasn't expecting. That can of course also be used to implement an iterator for a collection, but it seems much more general.

Given that before generics Go had exactly 3 types of collections, and that those were all iterable with range, I guess I never thought about this thing missing from the for loop.


Iterator is not only about collections. Its not as powerful as a yield around continuations but you can return whatever you like.

~15 (?) years ago I wrote a "famous" blog post on how to use Iterator as a poor man Maybe/Option.

   for (String s: m Option<String>) {
     // Executed on Some
   }


An idomatic way to do this now is to start a goroutine and range over a channel it writes to. Less ergonomic and more error prone, but it works.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: