[quote=“ker, post:17, topic:1729”]type bool = Option<()>; const false: bool = Some(()); const true: bool = None;[/quote]
I’m irrationally fascinated by this, but think we can do better now that we have another 18 months of language progress:
type bool = Result<(),()>;
const false: bool = Err(());
const true: bool = Ok(());
fn careful_div(a: i32, b: i32) -> Result<i32,()> {
(b != 0)?;
a / b
}
(Aside: does <(),()> look like an owl to anyone else?)
More seriously, if A { B } currently means if A { B } else { () }, right? If we wanted to do this, it feels like it might be best done in the language, like letting loop return non-unit was.
if A { B } could (ignoring back-compat) be changed to mean if A { Some(B) } else { None }. Existing cases would be Some(()) (that looks familiar…) instead of (), but that doesn’t make me sad. (This is, of course, exactly what ker’s macro does. I agree that none of the closure syntaxes were great.)
And then the function in the OP would be
fn divide(numerator: f64, denominator: f64) -> Option<f64> {
if denominator != 0.0 {
numerator / denominator
}
}
That’s pretty elegant, actually…