Basic Usage

Comprehensive guide to using MathHook including expression creation with macros and constructors, simplification, pattern matching, symbol manipulation, number types, constants, and function expressions.

Code Examples

Expression Creation - Macros

Create expressions using ergonomic macros

use mathhook::prelude::*;

let x = symbol!(x);
let y = symbol!(y);

// Simple arithmetic
let expr1 = expr!(x + y);
let expr2 = expr!(2 * x);
let expr3 = expr!(x ^ 2);

// Complex expressions with explicit grouping
let expr4 = expr!((x + 1) * (x - 1));

// Multi-term expressions
let expr5 = expr!(add: (2*x), (3*y), (-5));

Expression Creation - Constructors

Programmatic construction with explicit API

use mathhook::Expression;

// Numbers
let int = Expression::integer(42);
let float = Expression::float(3.14);
let rational = Expression::rational(3, 4);  // 3/4

// Operations
let sum = expr!(1 + 2);
let product = expr!(2 * x);

Simplification

Transform expressions to canonical form

let x = symbol!(x);

// Combine like terms
let expr = expr!(x + x);
let simplified = expr.simplify();
// Result: 2*x

// Apply identities
let expr = expr!(x * 1);
let simplified = expr.simplify();
// Result: x

// Evaluate constants
let expr = expr!(2 + 3);
let simplified = expr.simplify();
// Result: 5

Pattern Matching (Rust)

Inspect expression structure with pattern matching

use mathhook::Expression;

let x = symbol!(x);
let y = symbol!(y);
let test_expr = expr!(x + y);

match test_expr {
    Expression::Add(terms) => {
        println!("Addition with {} terms", terms.len());
    }
    Expression::Mul(factors) => {
        println!("Multiplication with {} factors", factors.len());
    }
    Expression::Pow(base, exp) => {
        println!("Power: base={}, exp={}", base, exp);
    }
    _ => {}
}

Number Types

Different number representations in MathHook

// Integers (exact, arbitrary precision)
let int = Expression::integer(123456789);

// Rationals (exact fractions)
let frac = Expression::rational(22, 7);  // 22/7 ā‰ˆ Ļ€

// Floats (approximate)
let float = Expression::float(3.14159265359);

// Complex numbers
let complex = Expression::complex(
    Expression::integer(3),
    Expression::integer(4)
);  // 3 + 4i

Mathematical Constants

Built-in mathematical constants

let pi = Expression::pi();
let e = Expression::e();
let i = Expression::i();              // imaginary unit
let phi = Expression::golden_ratio();
let gamma = Expression::euler_gamma();

Function Expressions

Create elementary function calls

// Elementary functions using expr! macro
let sin_x = expr!(sin(x));
let cos_x = expr!(cos(x));
let log_x = expr!(log(x));

// Or using function! macro
let tan_x = function!(tan, x);

šŸ”— Related Topics