23Aug

Rust, back to the basics, and then being snarky about it.

Posted by Elf Sternberg as Uncategorized

I’ve decided, for the sake of insanity, to work my way through the O’Reilly Programming Rust book, since I feel like my Rust has become, shall we say, rusty. And I’m doing it with my usual sense of attitude, that "There has to be a better way!"

First, I took this mess from the very first example (another greatest common denominator function… you’d think tutorial writers would figure out most of us would rather write something useful, ne):

let mut numbers == Vec::new();
for arg in std::env::args().skip(1) {
        numbers.push(u64::from_str(&arg)
                     .expect('error parsing argument'));
}

And said, "I know there are way to initialize and map values automatically in other languages. Rust should too." And I dug through the documentation and discovered, why yes, Rust does:

let numbers = Vec::from_iter(
    std::env::args().skip(1)
        .map(|x| u64::from_str(&x).expect("Error parsing argument")));

That’s pretty dense, but it does the job, and it uses the exact same allocations, too.

The next step was the actual reduction (I’d already written the GCD function in a library):

let mut d = numbers[0];
for m in &numbers[1..] {
    d = gcd(d, *m);
}

Could I one-liner that? Why yes:

    let d = &numbers[1..].iter().fold(numbers[0], |acc, x| gcd(acc, *x));

I know there are people who hate this kind of programming, but I dunno, I find it much more readable. It says that d is a reduction via GCD of all the numbers in a container. It’s actually less confusing than the loop.

To me, at least.

1 Response to Rust, back to the basics, and then being snarky about it.

Greg Bell

August 23rd, 2018 at 4:04 pm

Well, to understand the first you just have to have seen a for loop, sequence operator, array notation, and assignment operator in any language before.

That leaves understanding & (maybe address/reference?) and * (maybe dereferencing?)

For a tutorial, that might be just the right amount of new stuff to be introducing in one example.

In your full-idiomatic rewrite, the reader needs to know the above plus what fold is, what the |s do, how acc gets initialised, as well as needing to have seen iter in another language.

Only “much more readable” if you’re fully versed in the idioms of rust.

Comment Form

Subscribe to Feed

Categories

Calendar

August 2018
M T W T F S S
« Jul   Sep »
 12345
6789101112
13141516171819
20212223242526
2728293031