I'm only at the beginning of learning Haskell, and currently I'm exploring the possibilities of lists. I wanted to sum up two lists, but somehow it went wrong.
So:
Input: sumTwoLists [2,5,7,7,9] [1,2,2] (basically 25779 + 122)
Output: [2,5,9,0,1]
First of all, I reversed the whole list, because the addition of multi-digit numbers must start at the end:
reverseList :: [Int] -> [Int]
reverseList [] = []
reverseList (x:xs) = reverseList xs ++ [x]
It works. Then I implemented an add function:
add :: (Num a) => [a] -> [a] -> [a]
add _ [] = []
add [] _ = []
add (x:xs) (y:ys) = (x + y) : add xs ys
But when one list is shorter, than another it goes wrong. (add [2,5,7,7,9] [1,2,2] = [3,7,9]) So finction must also add 0 to the end of the lower number ([1,2,2] = [1,2,2,0,0].)
And after that I tried to implement the sumTwoLists function like that:
sumTwoLists :: [Int] -> [Int] -> [Int]
sumTwoLists (x:xs) (y:ys) = reverseList ((reverseList (x:xs)) add (reverseList (y:ys)))
But this code does not take into account the fact that the elements cannot be greater than 9. I don't want to convert the elements into Int or Integer, that's why I do not use any of them.
I just basically want to reverse the lists, then add 0 in the shortest list, then sum up each element with an element from the other list and if the outcome is >9, then the result is divided by 10 (mod?) and the adjacent number is increased
For any help I would be very thankful!