In today’s Programming Praxis exercise, we’re going to add addition, subtraction and multiplication to our big number library. Let’s get started, shall we?
Addition and multiplication are both functions of the Num typeclass, so we add the two functions (the fact that a – b is equal to a + (-b) is already present in the Num typeclass, so since we already defined negate we don’t need to define the subtraction function) in our Num instance:
instance Num BigNum where
For addition, we need to decide whether we’re adding or subtracting, which we do for each pair of digit groups. We could do this digit by digit, but I’m going to be lazy and do it per group. The conversion to and from Integers is not needed now, but will be required once the base is increased to prevent overflowing the Int type.
a@(B l1 ds1) + b@(B l2 ds2) = B (length ds * signum l) ds where B l _ = if abs b > abs a then b else a ds = f 0 $ (if abs b > abs a then flip else id) (prep $ if signum l1 == -signum l2 then (-) else (+)) ds1 ds2 prep op (x:xs) (y:ys) = op (toInteger x) (toInteger y) : prep op xs ys prep _ xs ys = map toInteger $ xs ++ ys f r (x:xs) = let (d,m) = divMod (r + x) base in fromIntegral m : f d xs f r [] = if r == 0 then [] else [fromIntegral r]
For multiplication we use the grade school method of multiplying each digit group (again, instead of per-digit) and summing them up at the end.
(B l1 ds1) * (B l2 ds2) = B (signum l1 * signum l2 * sl) sds where B sl sds = sum $ mult ds1 ds2 mult (x:xs) (y:ys) = fromIntegral (toInteger x * toInteger y) : map shift (mult xs (y:ys)) ++ map shift (mult [x] ys) mult _ _ = [] shift (B l ds) = B (l + 1) (0 : ds)
Some tests to see if everything is working properly:
main :: IO () main = do print $ 12345678 + 987654321 == ( 999999999 :: BigNum) print $ 12345678 - 987654321 == (-975308643 :: BigNum) print $ 987654321 - 12345678 == ( 975308643 :: BigNum) print $ -12345678 + 987654321 == ( 975308643 :: BigNum) print $ -12345678 - 87654321 == ( -99999999 :: BigNum) print $ 12345678 * 87654321 == ( 1082152022374638 :: BigNum) print $ 12345678 * (-87654321) == (-1082152022374638 :: BigNum) print $ -12345678 * 87654321 == (-1082152022374638 :: BigNum) print $ -12345678 * (-87654321) == ( 1082152022374638 :: BigNum)