Macro polyeval::horner

source ·
macro_rules! horner {
    ($x:expr; [$($coeffs:expr),+ $(,)?]) => { ... };
    ($x:expr; $a:expr $(,)?) => { ... };
    ($x:expr; $a:expr, $($rest:expr),+ $(,)?) => { ... };
    (let $x:expr; $($t:tt)*) => { ... };
}
Expand description

Evaluate a polynomial with Horner’s method.

The coefficients are listed from zeroth order to highest.

At least one coefficient must be present; the coefficients may be enclosed in square brackets; a trailing comma is allowed at the end of the coefficients.

If the first token is the keyword let, then the x argument is evaluated only once.

§Usage

The macro can be invoked in any of the following ways:

  • horner!(x; a₀, a₁, ..., aₙ),
  • horner!(x; a₀, a₁, ..., aₙ,),
  • horner!(x; [a₀, a₁, ..., aₙ]),
  • horner!(x; [a₀, a₁, ..., aₙ,]),
  • horner!(let x; a₀, a₁, ..., aₙ),
  • horner!(let x; a₀, a₁, ..., aₙ,),
  • horner!(let x; [a₀, a₁, ..., aₙ]),
  • horner!(let x; [a₀, a₁, ..., aₙ,]).

In every case it computes the polynomial aₙxⁿ + ... + a₁x + a₀ using Horner’s method, i.e. a₀ + x*(a₁ + x*( ... + x*aₙ...)).

§Examples

use polyeval::horner;

let x = 7;

assert_eq!(horner!(x; [0]), 0);
assert_eq!(horner!(x; [0,]), 0);
assert_eq!(horner!(x; 0), 0);
assert_eq!(horner!(x; 0,), 0);

assert_eq!(
    horner!(x; 2, 3, 4),
    2 + x * (3 + x * 4)
);

assert_eq!(
    horner!(x; [2, 3, 4]),
    2 + x * (3 + x * 4)
);