Skip to main content

Rule

Struct Rule 

Source
pub struct Rule { /* private fields */ }
Expand description

A named rewrite rule lhs → rhs over expressions of one Context.

Symbols in lhs whose names end in _ are wildcards; a name ending in __ is a sequence wildcard that absorbs the remaining terms of an Add/Mul (see the Ex::rewrite docs). The right-hand side is either a template expression (wildcards are substituted) or a closure receiving the Bindings.

Rules are Clone + Send + Sync.

§Examples

use symplex::prelude::*;
use symplex::macros::Rule;

let ctx = Context::new();
let (x, a) = (ctx.symbol("x"), ctx.symbol("a_"));

// Template rule: exp(ln(a_)) → a_
let r = Rule::new("exp_ln", &a.ln().exp(), &a);
assert_eq!(r.apply(&x.ln().exp()), Some(x.clone()));
assert_eq!(r.apply(&x.exp()), None);

// Guarded rule: only fire when the bound value is a number.
let g = Rule::new_with_guard("sin_num", &a.sin(), &ctx.int(0), |b| {
    b.get("a_").is_some_and(|v| v.expr_type() == ExprType::Number)
});
assert!(g.apply(&x.sin()).is_none());
assert_eq!(g.apply(&ctx.int(7).sin()), Some(ctx.int(0)));

Implementations§

Source§

impl Rule

Source

pub fn new(name: impl Into<String>, lhs: &Ex, rhs: &Ex) -> Rule

Build a template rule lhs → rhs.

Wildcards in rhs that do not occur in lhs are left as literal symbols in the output; use try_new to reject such rules.

§Panics

Panics if lhs and rhs belong to different contexts.

Source

pub fn try_new( name: impl Into<String>, lhs: &Ex, rhs: &Ex, ) -> Result<Rule, SymplexError>

Like new, but returns an error when rhs mentions a wildcard that is not bound by lhs, or when lhs has no structure at all (a bare wildcard would match everything).

§Examples
use symplex::prelude::*;
use symplex::macros::Rule;

let ctx = Context::new();
let (a, b) = (ctx.symbol("a_"), ctx.symbol("b_"));
assert!(Rule::try_new("bad", &a.sin(), &b).is_err());
assert!(Rule::try_new("ok", &a.sin(), &a).is_ok());
Source

pub fn new_with_guard( name: impl Into<String>, lhs: &Ex, rhs: &Ex, guard: impl Fn(&Bindings) -> bool + Send + Sync + 'static, ) -> Rule

Build a template rule with a guard: the rewrite fires only when guard(&bindings) returns true.

The guard runs without holding the context lock, so it may call any Ex method (e.g. is_positive(), is_number()).

§Panics

Panics if lhs and rhs belong to different contexts.

Source

pub fn new_fn( name: impl Into<String>, lhs: &Ex, f: impl Fn(&Bindings) -> Option<Ex> + Send + Sync + 'static, ) -> Rule

Build a rule whose right-hand side is computed by a closure.

Returning None from the closure means “does not apply” (the next match / rule is tried). The returned expression must belong to the same context as lhs.

§Examples
use symplex::prelude::*;
use symplex::macros::{Rule, RuleSet};

let ctx = Context::new();
let (x, a) = (ctx.symbol("x"), ctx.symbol("a_"));
// Evaluate ln of perfect powers of e: ln(exp(a_)) → a_ only if a_ is a number.
let r = Rule::new_fn("ln_exp_num", &a.exp().ln(), |b| {
    let v = b.get("a_")?;
    (v.expr_type() == ExprType::Number).then(|| v.clone())
});
let rules = RuleSet::from_rules(vec![r]);
assert_eq!(format!("{}", ctx.int(3).exp().ln().rewrite(&rules)), "3");
assert_eq!(format!("{}", x.exp().ln().rewrite(&rules)), "ln(exp(x))");
Source

pub fn from_macro_rule(ctx: &Context, rule: Rule) -> Rule

Wrap an arena-level rule produced by the rule! macro (built inside ctx.with_arena_mut(|arena| ...)).

§Examples
use symplex::prelude::*;
use symplex::macros::{Rule, RuleSet};

let ctx = Context::new();
let x = ctx.symbol("x");
let raw = ctx.with_arena_mut(|arena| rule!(arena, "pyth", sin(w_)^2 + cos(w_)^2 => 1));
let rule = Rule::from_macro_rule(&ctx, raw);
let rules = RuleSet::from_rules(vec![rule]);
let expr = &x.sin().powi(2) + &x.cos().powi(2) + 2;
assert_eq!(format!("{}", expr.rewrite(&rules)), "3");
Source

pub fn name(&self) -> &str

The rule’s name.

Source

pub fn lhs(&self) -> &Ex

The left-hand side (pattern) expression.

Source

pub fn wildcards(&self) -> Vec<String>

Names of the wildcards bound by this rule’s left-hand side.

Source

pub fn matches(&self, expr: &Ex) -> Option<Bindings>

Match the rule’s left-hand side against the whole of expr (no traversal, no partial Add/Mul match) and return the bindings on success. Guards are honoured.

Source

pub fn apply(&self, expr: &Ex) -> Option<Ex>

Apply the rule at the root of expr (no traversal).

For an Add/Mul subject the pattern may match a subset of the terms; the remaining terms are re-attached to the replacement. Returns None if the rule does not apply.

Trait Implementations§

Source§

impl Clone for Rule

Source§

fn clone(&self) -> Rule

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Rule

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl FromIterator<Rule> for RuleSet

Source§

fn from_iter<I: IntoIterator<Item = Rule>>(iter: I) -> Self

Creates a value from an iterator. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Rule

§

impl !UnwindSafe for Rule

§

impl Freeze for Rule

§

impl Send for Rule

§

impl Sync for Rule

§

impl Unpin for Rule

§

impl UnsafeUnpin for Rule

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more