malachite_q/conversion/
from_bool.rs

1// Copyright © 2025 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::Rational;
10use malachite_base::num::basic::traits::{One, Zero};
11
12impl From<bool> for Rational {
13    /// Converts a [`bool`] to 0 or 1.
14    ///
15    /// This function is known as the [Iverson
16    /// bracket](https://en.wikipedia.org/wiki/Iverson_bracket).
17    ///
18    /// $$
19    /// f(P) = \[P\] = \\begin{cases}
20    ///     1 & \text{if} \\quad P, \\\\
21    ///     0 & \\text{otherwise}.
22    /// \\end{cases}
23    /// $$
24    ///
25    /// # Worst-case complexity
26    /// Constant time and additional memory.
27    ///
28    /// # Examples
29    /// ```
30    /// use malachite_q::Rational;
31    ///
32    /// assert_eq!(Rational::from(false), 0);
33    /// assert_eq!(Rational::from(true), 1);
34    /// ```
35    #[inline]
36    fn from(b: bool) -> Self {
37        if b { Self::ONE } else { Self::ZERO }
38    }
39}