Module rust2fun::data::validated

source ·
Expand description

Error handling with the Validated type.

Validated<T, E> is the type used for returning and propagating errors. It is an enum with the variants, Valid, representing success and containing a valid value, and Invalid, representing error and containing an error value.

Validated is very similar to Result in that Valid corresponds to Ok and Invalid corresponds to Err. The difference is that Validated is designed for use cases in which it may be more convenient to collect all of the errors that have occurred, rather than stopping at the first error encountered.

Note that unlike Result Validated is not a monad, but it is an applicative functor, so it is possible to use it with functions that operate on Validated values in an applicative style.

Examples

use rust2fun::prelude::*;

fn validate_number(number: CreditCardNumber) -> ValidatedNev<CreditCardNumber, Error> {
    unimplemented!("Validate credit card number")
}

fn validate_expiration(date: Date) -> ValidatedNev<Date, Error> {
    unimplemented!("Validate credit card expiration date")
}

fn validate_cvv(cvv: Code) -> ValidatedNev<Code, Error> {
    unimplemented!("Validate credit card cvv")
}

fn validate_credit_card(
    number: CreditCardNumber,
    expiration: Date,
    cvv: Code,
) -> ValidatedNev<CreditCard, Error> {
    ValidatedNev::pure(CreditCard::new)
        .ap3(validate_number(number),
             validate_expiration(expiration),
             validate_cvv(cvv))
}

// Alternative implementation using `map3`:
fn validate_credit_card_alt(
    number: CreditCardNumber,
    expiration: Date,
    cvv: Code,
) -> ValidatedNev<CreditCard, Error> {
    MapN::map3(validate_number(number),
               validate_expiration(expiration),
               validate_cvv(cvv),
               CreditCard::new)
}

Re-exports

Enums

Type Aliases