7 ms·
let descending_squares = range(0u, 5u).rev().map(|x| x * x).collect(); versus: let mut descending_squares = Vec::new(); let mut i = 4u; loop {
by pcwalton 12y ago
let descending_squares = range(0u, 5u).rev().map(|x| x * x).collect();
versus:
let mut descending_squares = Vec::new();
let mut i = 4u;
loop {
descending_squares.push(i * i);
if i == 0 {
break
}
i -= 1
}
(Note that if you try to use a for loop here you will infinite loop due to unsigned underflow.)
- jaekwon 12y agoWell this is how I'd write it in Go: descending_squares := []uint{} for x:=4; 0<=x; x-- { descending_squares = append(descending_squares, uint(x*x)) }
- pcwalton 12y agoUse unsigned integers for your index and values. That's what makes it hard to use a for loop. (Sure, you could cast a signed integer loop index to unsigned inside the loop to avoid the underflow problem in this specific case, but I'd argue that the functional style is so much clearer than code that has to work around unsigned underflow gotchas.)
- jaekwon 12y agoAll I did was take your for-loop code and translated into idiomatic Go code. My point is the for-loop in Go isn't as terrible as the loop example you wrote.
- pcwalton 12y agoYour version infinite loops: http://play.golang.org/p/uglbTETE6d http://play.golang.org/p/uglbTETE6d See why for loops are tricky? :)
- jaekwon 12y agoDoh! I fell straight in :) Overflows in general are tricky. How does Rust deal with it?
- pcwalton 12y agoWe have special checked types you can use if you want checked arithmetic. The default is to not check, because CPUs currently make it expensive to check (although I would love it if that could change--we need hardware support though).
- jaekwon 12y agoNice. :)
- acqq 12y agoBut CPU's have the overflow flag, that is actually set if the operation overflows? You can't write that check explicitly in C, but you can in assembler. Available now, across the different hardware.
- dbaupp 12y agoAs you say, detecting the overflow is easy, but efficiently handling it is not. It adds a branch to every single arithmetic operation, and it makes it much harder for the compiler to optimise things e.g. it is hard to vectorise a loop summing an array, if every + has a conditional branch on the overflow flag. (Also, I believe it introduces a lot of data dependencies, getting in the way of the out-of-order execution of modern CPUs.)
- acqq 12y agoTo handle the overflow on the places where you want to handle them, modern processor doesn't have any problem with an additional jump instruction. Also, modern compilers could optimize the checks away if they aren't used. In effect, implementing overflow checks definitely won't turn your C speed (1s) code in a Python speed (40s) code. I estimate it wouldn't be even two times slower in most of the use cases. It's certainly not the problem of the CPU's. It can be the problem of the certain compilers if they don't have the infrastructure to reason about overflow flags though. But it's not a hardware problem.
- codygman 12y agoI love when arguments are decided by/proven by runnable code examples.
- hit8run 12y agoJust use int and it works fine: http://play.golang.org/p/nZcd3M5aL_ http://play.golang.org/p/nZcd3M5aL_ To me golang is readable while even small rust examples don't feel quite right right.
- masklinn 12y ago> Just use int and it is a completely different piece of code.
- gorhill 12y ago> functional style is so much clearer There is something that makes me uncomfortable in there: > let descending_squares = range(0u, 5u).rev().map(|x| x * x).collect(); The overhead. I wonder about it. I am unable to get a sense of what it is. With a simple for-loop, it's rather easy to see it, but with the version above I have no idea. So "much clearer" is not what I see with the piece of code above. I see what it does, but what is not so clear is what code will be generated, something which matters when trying to write efficient code.
- dbaupp 12y agoThere is not much overhead with Rust iterators at all. They are essentially concrete versions of the deforestation that Haskell can do to avoid constructing intermediate lists, and compile to code that is close to the equivalent C (the functionality is all statically dispatched, so the compiler can inline and optimise the calls). This is a case of having experience with and trusting one's tools. I wrote a blog post a while ago that used iterators heavily http://huonw.github.io/blog/2014/06/comparing-knn-in-rust/ http://huonw.github.io/blog/2014/06/comparing-knn-in-rust/ , as you can see the performance is good.
- gorhill 12y agoI am definitely going to have to look more into Rust.
- kinghajj 12y agoWell then, good news! Such usages of iterators in Rust are almost always result in the same code that would be generated by old-fashioned, hand-written loops. The 'trick' is that the methods (and the closure!) are inlined, and generics are specialized at compile time.
- jksmith 12y agoOr if Go and Rust had a FOR loop guaranteed to stop at 0, as with a Wirthian language, no?
- steveklabnik 12y agoYou need a collect on that first example, you end with a Vec<uint> in the second, but an Iterator<something> in the first.
- pcwalton 12y agoOops, you're right. Fixed.
- NateDad 12y agoAnd that's why I like go. Sorry, that's not really fair. I'm sure the compiler would have caught that when you tried to feed it into something that wanted a vector (or would have not cared if you were just iterating over it). To be honest, I think Rust has a lot going for it. I just think Go has a lot going for it too... they're just different things. Which is fine, because if everything were the same, the world would be a really boring place. :)
- kxo 12y agoAre you suggesting the Rust compiler didn't catch that?
- NateDad 12y agoNo? I don't actually know rust, but I don't think the first thing he typed was invalid code. It just returned an iterator instead of a vector. I was suggesting that when he tried to pass the variable into a function that expected a vector, the compiler would complain. No snark, I just meant what I said.
- kibwen 12y agoTo be fair, the line "And that's why I like go" seems to imply that Go is able to keep you from making errors in untested context-free code snippets. Perhaps you meant "and that's why I like that Go doesn't support operations like `map`"?
- hammerandtongs 12y agoAside from your specific point (which I liked), isn't there a kind of tension here in a systems language? For loops are almost always going to explicitly show their allocations whereas the functional version has allocations that are not nearly as obvious.
- pcwalton 12y agoNone of the iterators in the Rust core library allocate. (In fact, they can't, since the Rust core library has no allocation—it's the building block for liballoc.)
- NateDad 12y agoGo is not the language for you if you care about mashing as much logic into a single line as you can. Also, I can count the number of times in my 15 years of professional development experience that I've wanted to count down to zero using an unsigned int as the index... never. Which is not to say that the declarative isn't nice, just saying that the example of the infinite loop is not exactly compelling.
- pcwalton 12y ago> Go is not the language for you if you care about mashing as much logic into a single line as you can. The point here is that iterators can reduce bugs, independent of aesthetic concerns. > Also, I can count the number of times in my 15 years of professional development experience that I've wanted to count down to zero using an unsigned int as the index... never. I like to give that example because it was something I actually hit and a bug that I actually had to fix. In fact I just hit that again yesterday when iterating over a list in reverse order (painting order for CSS box-shadow).
- zzzcpan 12y ago> The point here is that iterators can reduce > bugs, independent of aesthetic concerns. Iterators can reduce bugs, really? This is a very flawed point. Bugs are not caused by lack of language features, they are caused by people. And people make mistakes independent of language features and sometimes because of language features causing cognitive overload or require them to make assumptions.
- Dewie 12y agoThe way I see it is that you can reduce bugs by increasing the level of abstraction, which in this case means to use things that are more straightforward and less flexible: the ultimate looping-construct is arguably the while-loop, by using a counter to index into the array (if you're working with an array, anyway). But with that flexibility comes more room for error: maybe your increment is wrong, maybe your while-condition is wrong, maybe you inadvertently change the index inside the loop without meaning to, etc. A step over that is to explicitly just say that you want to iterate over each element in the array. You don't get to choose how, but you probably wanted to iterate over it from start to finish anyway. The highest level is a function that encapsulates exactly what you want without having to bother with explicitly iterating over the collection yourself. Now you can't even mess up how you use each member of the array, because that is already handled by the function. A higher level of abstraction means less flexibility, which means fewer potential things that you can screw up. I don't see how that is a flawed point.
- tspiteri 12y agoThat's the only place in C where I use the postfix decrement operator. for (u = 5; u-- > 0; ) {