Monday, July 18, 2005

The Natural Numbers

One of the statements in my calculus language is the operator declaration:
Neg operator "~" has arity 1, fixity 0, priority 1.
As negative numbers don't really make much sense as the arity and fixity of an operator, I've just spent a while knocking up a Haskell implementation of the natural numbers.

While I dislike programming in Java and other "OO" languages, they do make it a lot easier to extend types than is the case in Haskell. It would be much easier to do this sort of thing if Haskell supported instance declarations (the things that make most polymorphic functionality work in Haskell) on type synonyms. If it did, Natural.hs would be about 6 lines of code (plus a few lines of boiler plate) rather than nearly 60 lines.

My new type Natural (just a wrapper around Integer) is an instance of eight separate type classes:
  1. Eq (they can be compared for equality)
  2. Ord (values can be ordered with respect to each other)
  3. Show (values can be converted to strings)
  4. Read (values can be parsed out of strings)
  5. Bounded (the range of values is bounded), though Natural shouldn't have an upper bound
  6. Enum (values can be enumerated)
  7. Num (values are numbers)
  8. Real (values are real numbers)
  9. Integral (values are integral numbers)
It probably ought to have a few more like:
  • Random (values can be randomly generated); and
  • Ix (values can used as array indices)
but it'll get the job done -- all I need from it is Eq and Ord.

No comments: