Impl Try for bool

Can we have this?

impl Try for bool {
    type Ok = ();
    type Error = ();

    fn into_result(self) -> Result<(), ()> {
        if self { Ok(()) } else { Err(()) }
    }

    fn from_error((): ()) -> bool {
        false
    }

    fn from_ok((): ()) -> bool {
        true
    }
}

I want this quite often when I want to do a bunch of checks and get false if any of the checks return false. Having bool implement Try will mean I can do that without using chains of combinators.

As far as I’m concerned bool is basically just shorthand for Option<()> which is basically just shorthand for Result<(), ()>, and we already have this for Option<T> and Result<T, E>.

3 Likes

Speaking of which, it’d be nice to have functions to downcast from Result<(), ()> to Option<()> and Option<()> to bool. Result::ok and Option::is_some can be used but I’d like functions that explicitly don’t throw away any data.

1 Like

Some previous places this has come up:

And of course there’s

I’d personally have no complaints with bool: Try.

+999, but it needs to be type Error = FalseError for the same reason of NoneError.

1 Like

Unfortunately, I don’t think this will have the right precedences: !cond?. That alone makes me a bit skeptical that this is a good idea. This won’t compile but having to write (!cond)? is a bit surprising.

2 Likes

The version with parentheses looks more readable to me, so I don’t mind that they’re required there.

3 Likes

Can you show an example of the kind of code you want to write?

Would && help you here?

1 Like

Maybe it’d suffice to add equivalent of .ok_or() to bool?

boolean_result().true_or(Error::FalsyThing)?;
2 Likes

Zero / false meaning success is perhaps not as common as zero / false meaning failure, but it is commonly encountered – for instance both Unix and Windows system calls use zero for success and some nonzero code for failure (if they don’t have some other token to return). So I do not think this mapping is universal enough to be put in the stdlib, and unfortunately that torpedoes the entire concept.

3 Likes

If we can have false_or as well, then I do endorse this idea.

2 Likes

That’s much less common when using an actual bool type.

But I do agree that the semantics and types seem like they shouldn’t be in std/core.

You end up having the same polarity problem with Option and Result though. Occasionally I want to write code that returns early on the first Ok (or Some) but otherwise runs to the end collecting errors.

1 Like