this post was submitted on 08 Dec 2023
623 points (96.4% liked)

Programmer Humor

32710 readers
1430 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 5 years ago
MODERATORS
 
you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 12 points 1 year ago (1 children)

Other languages: if a is null return b.

Rust: here is an array of strings, we are going to parse the array to numbers. If that conversion fails we handle the exception and return the minimum integer value. We then save the result in a new vector. We also print it.

I like rust, but I hate the example too. It's needlessly complex. Should have just been a.unwrap_or(b).

[–] [email protected] 3 points 1 year ago* (last edited 1 year ago) (1 children)

The example even used unwrap_or_else where they should use unwrap_or. Then it uses std::i64::MIN as fallback value where they could use something like 0 that would be a better example and honestly make more sense there.

let parsed_numbers = ["1", "not a number", "3"]
    .iter()
    .map(|n| n.parse().unwrap_or(0))
    .collect();

// prints "[1, 0, 3]"
println!("{:?}", parsed_numbers);

Even without trimming this to something less convoluted, the same functionality (with different fallback value) could be written in more readable form.

Obviously in the context of the page something like this would make way more sense:

maybe_number.unwrap_or(0)

Or perhaps more idiomatic version of the above:

maybe_number.unwrap_or_default()
[–] words_number 2 points 1 year ago (1 children)

I think you could even get rid of the iter() and the collect() since it's a small fixed size array.

[–] [email protected] 2 points 1 year ago* (last edited 1 year ago)

Yep [T;N] has a direct implementation of map. "{:?}" is necessary because arrays aren't Display but you could get around that by saying

["1", "not a number", "3"].map(|n| println!("{}", n.parse().unwrap_or(0)));

but now I'm golfing. Also

for n in ["1", "not a number", "3"] {
   println!("{}", n.parse().unwrap_or(0))
}

is more idiomatic I shouldn't let my Haskell get the better of me. That does use Iterator, not that it makes a difference here.