This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
shared interface DecisionTree<out Element, in Argument> of | |
Branch<Element,Argument> | Leave<Element,Argument> { | |
shared formal Element evaluate(Argument arg); | |
} | |
shared interface Branch<out Element,in Argument> satisfies DecisionTree<Element,Argument> { | |
//the predicate could be represented like this | |
//shared formal Callable<Boolean, [Argument]> predicate; | |
//but below we see the syntactic sugar declaration | |
shared formal Boolean(Argument) predicate; | |
shared formal DecisionTree<Element, Argument> left; | |
shared formal DecisionTree<Element, Argument> right; | |
shared actual Element evaluate(Argument arg) { | |
if (predicate(arg)) { | |
return left.evaluate(arg); | |
} else { | |
return right.evaluate(arg); | |
} | |
} | |
} | |
shared interface Leave<out Element, in Argument> satisfies DecisionTree<Element,Argument> { | |
shared formal Element element; | |
} | |
class Purchase(isMember, hasCoupon) { | |
shared Boolean isMember; | |
shared Boolean hasCoupon; | |
} | |
class PurchaseBranch(left, right, predicate) satisfies Branch<Float, Purchase> { | |
shared actual DecisionTree<Float,Purchase> left; | |
shared actual Boolean(Purchase) predicate; | |
shared actual DecisionTree<Float,Purchase> right; | |
} | |
class PurchaseLeave(element) satisfies Leave<Float, Purchase> { | |
shared actual Float element; | |
shared actual Float evaluate(Purchase arg) => element; | |
} | |
Boolean isMember(Purchase purchase) => purchase.isMember; | |
Boolean hasCoupon(Purchase purchase) => purchase.hasCoupon; | |
/** | |
isMember | |
| | |
_____________________________ | |
| | | |
true false | |
| | | |
hasCoupon hasCoupon | |
| | | |
______________ ________________ | |
| | | | | |
true false true false | |
| | | | | |
8 10 12 16 | |
running our program prints | |
8.0 | |
10.0 | |
12.0 | |
16.0 | |
**/ | |
void algebraic_demo() { | |
PurchaseBranch root = PurchaseBranch( | |
PurchaseBranch( | |
PurchaseLeave(8.0), | |
PurchaseLeave(10.0), | |
hasCoupon), | |
PurchaseBranch( | |
PurchaseLeave(12.0), | |
PurchaseLeave(16.0), | |
hasCoupon), | |
isMember | |
); | |
print(root.evaluate(Purchase(true, true))); | |
print(root.evaluate(Purchase(true, false))); | |
print(root.evaluate(Purchase(false, true))); | |
print(root.evaluate(Purchase(false, false))); | |
} | |
No comments:
Post a Comment