Define recurrent type of Integers representation to work like so:
data Integers = Zero | Next Integers | Prev Integers
and make this representation, the instance of class Num, it means that You should can use (+), (*), (==), abs, signum, show on Integers
Till now i defined sth like this:
data Integers = Zero | Integers Int deriving (Show)
next :: Integers -> Integers
next Zero = Integers 1
next (Integers a) = Integers a + Integers 1
prev :: Integers -> Integers
prev (Integers 1) = Zero
prev (Integers a) = Integers a - Integers 1
instance Eq Integers where
Zero == Zero = True
Integers a == Integers b = a == b
_ == _ = False
instance Num Integers where
Integers a + Integers b = Integers (a + b)
Integers a - Integers b = Integers (a - b)
Integers a * Integers b = Integers (a * b)
abs (Integers a) = Integers (abs a)
signum (Integers a) = Integers (signum a)
fromInteger a = Integers (fromInteger a)
But it doesn’t fit the data Integers = Zero | Next Integers | Prev Integers expectations
I’m going to show you
+, the rest should be easy enough.Well, that was easy!
Oh. There are some other cases.
Still, we’ve handled all the
Zerocases, so now we only have to deal withPrevandNext. They’re opposites of each other, aren’t they? So if we’re given one of each, they’ll cancel each other out.Now we only have to worry about the cases where the numbers we’re given both have the same sign.
(These last two equations are not the most efficient implementation, but they are straightforward to understand.)
And we’re done defining
+.Some of the other functions are easier, some are harder (and should reuse some of the easier functions), but they all involve pattern matching on the/either/both parameter(s) and doing the appropriate thing. And mostly they involve recursion, usually inescapable at some level when given a recursive data structure.