4 ms·
I don't think any of the common business programming languages let you add new types to the numeric tower. C++ does, through operator overloading. Haskell has
by jrockway 14y ago
I don't think any of the common business programming languages let you add new types to the numeric tower. C++ does, through operator overloading. Haskell has very nice support for this; to get started all you need is "newtype Money = Money Rational deriving (Show, Eq, Ord, Ratio, Integral, Num)". If you later want to make the type more restrictive than Rational, you can do that without changing any calling code (which will work on normal Num instances, most likely).
- dllthomas 14y agoUnfortunately, "Num" isn't precisely what you want in money - you don't multiply dollars by dollars to get dollars... But it works well enough.
- jrockway 14y agoRather than arbitrary multiplication, you should probably have an OrderUnits type, then define a function of type Money -> OrderUnits -> Money that calculates the price of multiple units. (Money 3 * 2 will return Money 6 if fromIntegral 2 = Money 2. But that is not really the operation you want to perform, so you might consider not implementing Num for Money.)
- dllthomas 14y agoRight, exactly.