Function contrafact::mapped[][src]

pub fn mapped<T, F, S>(reason: S, f: F) -> MappedFact<'static, T> where
    S: ToString,
    T: Bounds,
    F: 'static + Fn(&T) -> Facts<'static, T>, 
Expand description

A fact which is defined based on the data to which it is applied. It maps the data into a fact to be applied.

This can be useful for “piecewise” functions, where the constraint is fundamentally different depending on the shape of the data, or when wanting to set some subset of data to match some other subset of data, without caring what the value actually is, and without having to explicitly construct the value.

NOTE: since the returned Facts are generated brand-new on-the-fly, these Facts must be stateless. State changes cannot be carried over to subsequent calls when running over a sequence. (TODO: add StatelessFact trait to give type-level protection here.)

use contrafact::*;

// This contrived fact reads:
//   "if the number is greater than 9000,
//    ensure that it's also divisible by 9,
//    and otherwise, ensure that it's divisible by 10"
let fact = mapped("reason", |n: &u32| {
    if *n > 9000 {
        facts![ brute("divisible by 9", |n| *n % 9 == 0) ]
    } else {
        facts![ brute("divisible by 10", |n| *n % 10 == 0) ]
    }
});

assert!(fact.check(&50).is_ok());
assert!(fact.check(&99).is_err());
assert!(fact.check(&9009).is_ok());
assert!(fact.check(&9010).is_err());