logoalt Hacker News

fc417fc802yesterday at 8:37 PM2 repliesview on HN

For loops are hardly the only usecase and built in iteration constructs frequently fall short. For example any mildly complex loop that involves pointer juggling can benefit.

> which doesn't have the footguns of `++` due to assignment being a statement rather than expression,

So then I implement the local equivalent of inc( v ) and ... same issue, right? Plus with rust macros is there any technical reason you can't trivially implement ++ for yourself? That's the case for most lisps that I touched on earlier.


Replies

kibwenyesterday at 9:48 PM

> For example any mildly complex loop that involves pointer juggling can benefit.

I'd say that when you're writing a mildly complex loop that involves pointer juggling, one should prefer to be defensive and explicit rather than cleverly trying to compress everything into one-liners.

> So then I implement the local equivalent of inc( v ) and ... same issue, right?

This isn't done in Rust because there's no benefit. It's rare to find an occasion where it's necessary to do something tricky enough to forego using iterators, and when working with raw pointers Rust code just plain doesn't use basic addition for pointer arithmetic; instead it has a variety of pointer arithmetic methods for being explicit about the desired semantics (e.g. ptr::add, ptr::offset, ptr::wrapping_add, etc).

> Plus with rust macros is there any technical reason you can't trivially implement ++ for yourself?

There's not, but people might look at you sideways. Here, I implemented it for you: https://play.rust-lang.org/?version=stable&mode=debug&editio... . It expands to nested blocks with internal assignments, which results in a well-defined semantics following the defined order of evaluation in Rust.

marcosdumayyesterday at 11:16 PM

In Rust you hide all kinds of error prone iterations behind the "iterator" interface. Both the "for(int x=0;..." and the "while(list[i++])" are implemented at the standard library.

People tend to use FP abstractions for the "x[i++] = f(y[j++])" though, not iteration.