by imiric · 3y ago · 0 comments
I love Go because of its simplicity, and because it strictly adheres to the "there's only one way to do it" mantra. Adding syntax sugar muddles this, and introducing another keyword and construct makes the code less readable.
I hope that this proposal is rejected, and that it's not a sign of Go becoming yet another kitchen sink language.
It's rare that can is relevant when it comes to language design. You typically can do anything in any language.
Adding dedicated support for iterators would promote it as the way to iterate. That would actually simplify the language - one way to express a common need as opposed to the current mess of ~5 different ways [1]:
"In the standard library alone, we have archive/tar.Reader.Next, bufio.Reader.ReadByte, bufio.Scanner.Scan, container/ring.Ring.Do, database/sql.Rows, expvar.Do, flag.Visit, go/token.FileSet.Iterate, path/filepath.Walk, go/token.FileSet.Iterate, runtime.Frames.Next, and sync.Map.Range, hardly any of which agree on the exact details of iteration. Even the functions that agree on the signature don’t always agree about the semantics."
Go would have been a far simpler language had it originally shipped with generics, iterators, and sum types.
For example, generics were a highly controversial topic, and many people still believe that Go didn't need them. I'm partially in that camp. I've encountered maybe one or two situations where generics would've been convenient since Go 1.18, and in both cases not jumping straight at the opportunity to use them, but being forced to refactor and approach the solution in a different way, has produced simpler and more readable code. To this day, I struggle with Go's generics syntax, and it just looks alien to me.
Iterators are a useful feature, but are they really generally useful to deserve a change in the language spec? Like generics, I've yet to encounter a situation where they're truly required, and when I do, implementing them myself is trivial.
So, sure, language designers can cram every programming construct we've invented in the last 50 years, as Rust and Raku have done, and many programmers will find this very convenient and flexible, but a more focused and conservative approach produces a simpler language that is easy to pickup and read. This is what drew me to Go in the first place, and lately it seems that this is changing.
You have language features which are not needed for the ones using directly (for the lack of better term) the language and but really nice for the people providing building blocks for them.
I am using generics in other languages than Go but not in Go as I am normally not writing libraries in Go or they are already so specific that generics are not needed.
You forgot tuples.
func F() (A, B) { ... }
func G(a A, b B) { ... }
G(F())
Is the return value of F a tuple? Is the parameter list of G a tuple? Given H: func H(ab (A, B)) { ... }
How and when is H(F()) different from G(F())?(Before you suggest a Python-like star operator, personally I consider using it for non-homogenous arguments about as hygienic as keeping your toothbrush and dirty socks in the same drawer.)
Which assumes this code matters much, outside of errors for which intermediate processors can just take... a tuple of a value and an error.
Also assumes the magical splatting of MRVs is a good thing in the first place.
> (Before you suggest a Python-like star operator, personally I consider using it for non-homogenous arguments about as hygienic as keeping your toothbrush and dirty socks in the same drawer.)
That is literally what Go currently does for MRVs, except opt-in instead of magical.
There is nothing about such splatting which wouldn't work with proper tuples, if anything it's the opposite. It is, essentially, the value side of `uncurry`.
There is one. Return a channel. Just a bit iffy when you want to stop iteration in the middle and throw away the rest.
And in this case there is really no need to spawn goroutines to support iterators
programming is a lazy hobby. it's why as soon as generics were released, I immediately implemented 'Keys', 'Values', 'ToSet', etc. Writing multiple lines to do the equivalent of these functions might be 'pure' but it's not easier to read. Worse: instead of standardizing these common operations, you just have everyone rolling their own implementations of the exact same functions with slightly different naming/parameters/etc.
Am I confused in that there is some merit to this approach beyond dogma? Why do we, as a community, need to accept so few batteries? If you want to only use assembly in your code (the purest!), that's always an option.
Which is, looking at absolute hulking abomination C++ or Java has become, is the right approach in theory
They just made a massive miss with lack of generics and sum types on the start. They could've avoided nils entirely with that for example. Or have less annoying error handling.
TBF neither generics nor sum types were necessary for either, these could have been builtins or language-level features.
To start with it's not like Go has been shy about those for things they didn't want to formalise (yet), but even in languages where they're library-ish features it's common for them to have language-level support.
Being productive in a language is not just about using every convenience at your disposal, and typing less. It's about producing code that is easy to read and approachable for others or yourself years down the line. The more language features one needs to be aware of when writing or reading code, the less approachable it is.
Having less features also forces the programmer to rethink their solution in a less clever way. In dynamic languages like Python and Ruby it's very convenient to use some fancy trick to write less code. In languages like Rust or Raku, you can (ab)use some obscure feature in a non-intuitive way, and feel good about the "elegance" of the solution, but a fresh pair of eyes might struggle to understand what the code actually does. Considering reading code is much more important than writing it, as we literally write code for humans, not machines, optimizing for simplicity and having less features in a language is a more productive long-term approach.
Complexity is not something you can remove.
Complexity removed from language moves to the application.
The best thing you can do in the language is to make expressing complex concepts in easier, more clear way. Going too simple just produces more boilerplate and makes it harder to read.
That's the real value of "simple" languages like go.
I don't see why the author's implimentation is so complicated. I really just want an interface that works with the range operator, and to call it a day.
type Iterable[T any] interface {
Next() (T, bool)
}
so that for _, el := range someIterable {
}
is essentially the same as for el, ok := someIterable.Next(); ok; el, ok := someIterable.Next() {
}
I certainly think the first is more clear btw."go developers" is not a homogenous group. I write Go and am pretty happy with the language design as it is. I'm also fearful of it becoming a kitchen sink language because of a vocal minority who want Go to be more like language X, instead of just going and writing in language X.
There's plenty of things could be added to make code more concise, but they come with a hidden cost.
There is no new syntactic sugar nor there is a new keyword here though. It just changes how range works.
That being said, I'm not a fan of range having two modes of functionality. Perhaps it could just use an interface, now that we have generics it can be implemented on the existing supported types. And compiler can do whatever with it if it would be too slow.
The readability this provides is considerable.
Lets say the logic is:
for item := range list {
if condition(item) {
break
}
}
That is nice and readable, but if the thing your iterating is returning items in a batch then this gets far, far uglier. Its possible to end up with one loop that fetches x items at a time, and another that iterates over those items.. etc. But if you switch that to channels you maintain the readability and everything is nice! .. Except, you need a way to cancel the iteration, and it can't be closing the channel or the writer will panic. items, cancelFunc := apiCall()
for item := range items {
if condition(items) {
cancelFunc()
for _ := range items { }
break
}
}
close(items)
Now, this is even worse if you need some kind of finalization of the goroutine that spawns to write to the given channel. Now you have a wait group, or a second channel.. etc. If its possible to error in the middle of iteration then things get complicated as well. topLoop:
for _, batch := range list {
for _, item := range batch {
if condition(item) {
break topLoop
}
}
}
The language also supports a limited goto. Combined with select and context, I've never seen a situation I felt I couldn't adequately describe. type Iterator[T any] interface {
HasNext() bool
GetNext() T
}
And then use it like: for i.HasNext() {
current := i.GetNext()
// do things here
}
It's an extra line, sure, but it's pretty obvious what's going on.Iterator design is another area where sum types would help simplify things a lot. Just one method returning Some/None would be so much better.
It would be better, but since go has MRV and zero values
func Next() (hasNext bool, nextValue T)
works fine, this is not Java or C# where you need to split the protocol into two separate operations.If you're looking for those particular features, I'd recommend adopting go's `, ok` idiom that appears in several places in the language. A type like:
type Iterator[T any] interface {
Next() (T, bool)
}
Lets you write code like this, if that's more to your liking: for current, ok := i.Next(); ok; current, ok = i.Next() {
// do things here
}
Which, really seems like a more go-like way to do this in the language as well (ranging over a function then becomes syntactic sugar for the above).Slower. More complex. Why?!?
Just call your function in a loop.
It's awful, but they do it.
Why would that be slower?
... that's the theory behind it. For more grounded explanations, see [1] & [2].
What's the one way to do iterators now? I thought this proposal came about because there wasn't a default way and everybody had to roll their own.