by alfiedotwtf · 9y ago · 0 comments
return true if number > 2;
VS: if number > 2 {
return true
}
I find that one-liners like these are really ergonomic. let x = if number > 2 { "yes" } else { "no" };
It's not quite the same, and I'm not sure what the failure case would be if the 'else' statement was ommitted, but it comes close.After experimenting with Rust and Elixir I've really come to like the 'everything is an expression' approach. That and pattern matching can make some things really expressive.
If it's the last expression it will implicitly return the values. Easily fits on one line.
``` fn foo(number: u32) -> bool { if number > 2 { true } else { false } } ```
I mean obviously in this situation you could just have the body of the function be `number > 2` but I write a lot of Rust code that does similar things now.
sub compute_interest( $amount, $interest ) {
return $amount if $interest == 0; # Quick return
die "We don't allow computation of negative interest rates" if $interest < 0; # Throw an exception
# Do the actual work
...
}
Edit: Also, it's worth noting that Perl enforces some behavior on this by only allowing postfix conditionals to follow a single statement, not blocks, so it's not just a regular conditional with the order reversed.Other than that, early returns can simplify flow a lot - otherwise you may have to do massive nesting ifs or many flags. Or even goto or exceptions.
In both languages you can do the following:
return number > 2; return if($number > 2);
Is equivalent to: if($number > 2){
return;
} x = 42 if y > 7;
Rather than x = match y > 7 { true => 42, false => 0 };
Or even: foo() if bar();
Rather than: if bar() { foo() }