fp_library/classes/try_monoid.rs
1//! A trait for types that can be combined fallibly and have an empty value.
2//!
3//! This is similar to `Monoid`, but extends `TrySemigroup`.
4//!
5//! ### Examples
6//!
7//! ```
8//! use fp_library::{brands::*, classes::*, functions::*};
9//!
10//! let x = try_empty::<String>();
11//! assert_eq!(x, String::new());
12//! ```
13
14use super::{Monoid, TrySemigroup};
15
16/// A trait for types that can be combined fallibly and have an empty value.
17///
18/// This is similar to [`Monoid`], but extends [`TrySemigroup`].
19pub trait TryMonoid: TrySemigroup {
20 /// Returns the empty value.
21 ///
22 /// ### Type Signature
23 ///
24 /// `forall a. TryMonoid a => () -> a`
25 ///
26 /// ### Returns
27 ///
28 /// The empty value.
29 ///
30 /// ### Examples
31 ///
32 /// ```
33 /// use fp_library::{brands::*, classes::*, functions::*};
34 ///
35 /// let x = String::try_empty();
36 /// assert_eq!(x, String::new());
37 /// ```
38 fn try_empty() -> Self;
39}
40
41impl<T: Monoid> TryMonoid for T {
42 fn try_empty() -> Self {
43 Monoid::empty()
44 }
45}
46
47/// Returns the empty value.
48///
49/// Free function version that dispatches to [the type class' associated function][`TryMonoid::try_empty`].
50///
51/// ### Type Signature
52///
53/// `forall a. TryMonoid a => () -> a`
54///
55/// ### Type Parameters
56///
57/// * `A`: The type of the value.
58///
59/// ### Returns
60///
61/// The empty value.
62///
63/// ### Examples
64///
65/// ```
66/// use fp_library::{brands::*, classes::*, functions::*};
67///
68/// let x = try_empty::<String>();
69/// assert_eq!(x, String::new());
70/// ```
71pub fn try_empty<A: TryMonoid>() -> A {
72 A::try_empty()
73}