Implementing Natural Numbers in Haskell
My son Ulrik is teaching me mathematics these days, and the experience has made me want to look at Haskell programming again, since I realized that Haskell syntax was quite close to mathematical notation. Haskell is a really weird language for a dysfunctional programmer like myself. There are no loops, no objects and side effects are forbidden. On the upside it has pattern matching and type inference so that you don't have to sprinkle type declarations all over your code even though it is statically typed. For those totally unfamiliar with Haskell: Basics of Haskell or Learn You a Haskell for Great Good are introductions that I like.
What are the natural numbers anyway?
Ulrik taught me how we could define the natural numbers using only recursion with a function called Succ and a special value Zero.
We call our datatype N and we will assume that Zero is the zero value, (Succ Zero) is one, (Succ (Succ Zero)) is two and so forth. We've also defined a couple of shorthands to avoid having to write all these (Succ (Succ …..)) for the smallest numbers.
Numbers by themselves aren't that interesting so I wanted to see how difficult it would be to implement addition. Since these recursive Succ functions look a lot like lists we can think of addition as the same as splicing two lists into one.
The second clause of add matches (Succ n) which is basically the same as getting the tail. In the recursive call we take that tail effectively subtracting one from the first parameter and add a Succ (effectively adding 1) to the second parameter. When the first parameter is reduced to Zero we match the first clause and return the second parameter. I think of this as eating the first parameter and building up the second.
More readable numbers
Our numbers are very tedious to read with the auto generated instance of the Show typeclass that Haskell created for us when we said deriving Show. As an example 8 will look like this:
Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))))Since we don’t have division or modulo yet I don’t know how to make an algorithm to print them as decimals (other than converting to a Haskell Integer that is), so I thought we could convert to some sort of tally like representation. I decided to represent each Succ as a “|” but use a “$” for every fifth Succ.
Now 8 will look like this;
||||$|||which is a little easier to read. Notice that we removed Show from the deriving declaration for data N. Our last clause shows the common case where we add a “|” and recurse on the tail. We simply pattern match five Succ-s, call show on four, add the “$” and show the tail splicing together the result with the `++` list splicing operator.
Show as decimals
Let’s try to create a function that will print our numbers in decimal. As far as I remember you can sort of peel of the digits by integer division by 10 and the remainder will contain the last digit. Let’s write the decimalString function top down and we will see what other functions we will need.
We can see that we need a divmod function to do integer division and give the result together with the remainder. If we divide by ten we will remove the least significant digit from our number and the digit itself will be returned as the remainder. We also need a function succLowerThanTenToString to convert the digit to a string.
Integer division and remainder
I am just going to brute force division by using the fact that: x : y = z <=> z * y = x and just try z = one, and then Succ(z) until z * y = x. If z * y > x we have gone too far and we return the previous value of z together with the remainder. I named the “trying” variable maybeZ because we are trying to see if it might be the z from the equivalence in the beginning of the paragraph.
We need the function mult to do multiplication and minus to do subtraction. We also need `==` and `>`. Haskell has already provided us with `==` because of the deriving Eq statement in the definition of N. Let’s see if we can implement order by making N an instance of the Ord typeclass. The Haskell docs for the Ord typeclass says that we only need to implement one function; either `<=`or compare and the Ord typeclass will provide the `>` function that we need.
The next function we implement is minus.
We recurse down to the Zero eating up both arguments until we are left with the result of the subtraction and Zero. We note that minus for the natural numbers is a partial function since it is undefined when the first argument is smaller than the second, we choose to make that explicit by having an error for that case with an explanatory error message.
Get Syver Enstad’s stories in your inbox
Join Medium for free to get updates from this writer.
The mult function uses add to add the second factor a number of times corresponding to the first, again we “eat up” the argument by pattern matching with Succ.
Let us wrap up by changing our Show instance to use decimalString and also define what ten is:
Now we can get nice decimal notation prints in ghci.
*Main> (mult four $ add two three)
20








