Sum of two lists of newtype

Viewed 72

I created the type Big Number with the following functions

type Digits = [String]
type BigNumber = Digits

scanner :: String->BigNumber
scanner a = map (:[]) a

output :: BigNumber -> String 
output []=""
output a = head a ++ output(tail a)

I was trying to make a function that sums two BigNumbers like this:

somaBN :: BigNumber -> BigNumber -> BigNumber
somaBN a b = scanner (zipWith (+) (map read a)  (map read b))

that is supose to run like this:

[1,2,3]+[1,2,3]=[2,4,6]

But I get the error:

• No instance for (Num Char) arising from a use of ‘+’
• In the first argument of ‘zipWith’, namely ‘(+)’
  In the first argument of ‘scanner’, namely
    ‘(zipWith (+) (map read a) (map read b))’
  In the expression: scanner (zipWith (+) (map read a) (map read b))typecheck(-Wdeferred-type-errors)

How can I fix this?

1 Answers

zipWith (+) (map read a) (map read b) is a list of items with a type that is an instance of the Num typeclass. It thus makes no sense to use scanner, since this takes a String.

You thus should convert the numbers back to Strings with:

somaBN :: BigNumber -> BigNumber -> BigNumber
somaBN a b = map … (zipWith (+) (map read a :: Int) (map read b))

where you need to fill in … which is a function that transforms an Int into a String, hence … has type … :: Int -> String.

This will not take care of overflows. Indeed, if you use somaBN ["9"] ["9"], it will return ["18"], not ["1", "8"]. In case you need to work with overflow, likely you should use a recursive function.

Related