4 ms·
Type systems have their uses, but just pattern matching is sufficient here. In Prolog: eval(const(X), X). eval(add(L, R), S) :- eval(L, LV), eval(R, RV),
by silentbicycle 17y ago
Type systems have their uses, but just pattern matching is sufficient here. In Prolog:
eval(const(X), X).
eval(add(L, R), S) :- eval(L, LV), eval(R, RV), S is LV + RV.
eval(mul(L, R), P) :- eval(L, LV), eval(R, RV), P is LV * RV.
?- eval(const(6), Z).
Z = 6.
?- eval(mul(const(3), add(const(71), const(9))), Z).
Z = 240.
- jrockway 17y agoYou are right. This really has nothing to do with types. Java uses types for pattern matching since that's all the language allows pattern matching on. (Common Lisp is similar, but also has eql qualifiers.) The type system can be useful for more complex cases. Eventually you might have a good reason to represent each operation with its own type. In this case, typeclasses can remove redundant code. (For example, if you write a lazy evaluator for each type of operation, you can get the eager evaluator "for free", implemented in terms of the lazy evaluation in the typeclass definition. etc., etc. I am too tired to decide how this would happen in Java, but my gut instinct is "not cleanly".)
- silentbicycle 17y agoRight. If you're going to push that sort of checking on to the type system, then at least have a smart one.