Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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).



Unfortunately, "Num" isn't precisely what you want in money - you don't multiply dollars by dollars to get dollars...

But it works well enough.


Rather 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.)


Right, exactly.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: