[−][src]Trait egg::CostFunction
A cost function that can be used by an Extractor
.
To extract an expression from an EGraph
, the Extractor
requires a cost function to performs its greedy search.
egg
provides the simple AstSize
and AstDepth
cost functions.
The example below illustrates a silly but realistic example of implementing a cost function that is essentially AST size weighted by the operator:
struct SillyCostFn; impl CostFunction<SymbolLang> for SillyCostFn { type Cost = f64; // you're passed in an enode whose children are costs instead of eclass ids fn cost<C>(&mut self, enode: &SymbolLang, mut costs: C) -> Self::Cost where C: FnMut(Id) -> Self::Cost { let op_cost = match enode.op.as_str() { "foo" => 100.0, "bar" => 0.7, _ => 1.0 }; enode.fold(op_cost, |sum, id| sum + costs(id)) } } let e: RecExpr<SymbolLang> = "(do_it foo bar baz)".parse().unwrap(); assert_eq!(SillyCostFn.cost_rec(&e), 102.7); assert_eq!(AstSize.cost_rec(&e), 4); assert_eq!(AstDepth.cost_rec(&e), 2);
Associated Types
type Cost: PartialOrd + Debug + Clone
The Cost
type. It only requires PartialOrd
so you can use
floating point types, but failed comparisons (NaN
s) will
result in a panic.
Required methods
fn cost<C>(&mut self, enode: &L, costs: C) -> Self::Cost where
C: FnMut(Id) -> Self::Cost,
C: FnMut(Id) -> Self::Cost,
Calculates the cost of an enode whose children are Cost
s.
For this to work properly, your cost function should be
monotonic, i.e. cost
should return a Cost
greater than
any of the child costs of the given enode.
Provided methods
Loading content...Implementors
impl<L: Language> CostFunction<L> for AstDepth
[src]
type Cost = usize
fn cost<C>(&mut self, enode: &L, costs: C) -> Self::Cost where
C: FnMut(Id) -> Self::Cost,
[src]
C: FnMut(Id) -> Self::Cost,