[−][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:
use egg::{*, recexpr as r}; type Lang = &'static str; struct SillyCostFn; impl CostFunction<Lang> for SillyCostFn { type Cost = f64; // you're passed in an ENode whose children are costs instead of eclass ids fn cost(&mut self, enode: &ENode<Lang, Self::Cost>) -> Self::Cost { let op_cost = match enode.op { "foo" => 100.0, "bar" => 0.7, _ => 1.0 }; op_cost + enode.children.iter().sum::<f64>() } } let e: RecExpr<Lang> = r!("+", r!("foo"), r!("bar"), r!("baz")); 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.