How to add values ​​from two lists (+ additional condition) in Haskell

I am having a problem with this exercise. I tried to find him for a long time, but I cannot.

Define functions:

addLnat :: [Int] -> [Int] -> [Int]
mulLnat :: [Int] -> [Int] -> [Int]

      

addLnat adds numbers from two arrays, eg.

addLnat [4,5,6] [8,5,2] ->  [2,1,9]

      

since [4 + 8 gives 2 carry 1, 5 + 5 + 1 gives 1 carry 1, 6 + 2 + 1 = 9]

Lnat, is the "natural list number", represented as a list of the base 10 digits, least significant. So the number 654 is [4,5,6].

I got:

addLnat :: [Int] -> [Int] -> [Int]
addLnat _ [] = []
addLnat [] _ = []
addLnat (x:xs) (y:ys) = (if (x+y) > 9 then x+y-10 else (x+y)):(addLnat xs ys)

      

I add the number and ignore the carry. Not sure how to solve it. Any help would be much appreciated.


I improved the solution as per user5402's comment , so I created addLnat 'cr xs ys, but when I pass the carry as a parameter it doesn't load - most likely I'm getting the syntax wrong :( (cr is 0 just now and it will be replaced mathematics).

addLnat' c (x:xs) (y:ys) = d : addLnat' cr xs ys 
where d = if c+x+y < 9 then x+y else c+x+y-((quot (c+x+y) 10)*10) 
cr = 0 

      

Any ideas?

+3


source to share


2 answers


I am not very good with haskell, but maybe it can help;

add::[Int]->[Int]->[Int]
add x y = add' 0 x y

      

Here we define an add function that will use add 'to add two lists. The main idea is to "save" the transfer and work carefully with the corner cabinets. Here the transfer is stored in a "variable" rest



    add'::Int->[Int]->[Int]->[Int]
    add' 0 x []      = x 
    add' rest (x:[]) (y:[]) = [(r `mod` 10),(r `div` 10)]
       where r = x+y+rest
    add' y (x:xs) [] = add' (r `div` 10) ((r `mod` 10):xs) [] 
       where r = x+y
    add' rest (x:xs) (y:ys) = (r `mod` 10) : (add' (r `div` 10) xs ys)
       where r = x+y+rest 

      

List x must be larger than list y, but that's not a problem

add [5,7,8] [4,3,2]  => [9,0,1,1] (correct)
add [1,2,3] [4,5,6]  => [5,7,9,0] (correct)

      

+2


source


You need to write a version of addLnat that takes a carry parameter:

addLnat' c (x:xs) (y:ys) = d : addLnat c' xs ys
  where d = if c+x+y > 9 then ... else ...
        c' = ... the next carry bit ...

      



There are more details and corner cases, but this is the main idea. Finally,

addLnat xs ys = addLnat' 0 xs ys  -- initially the carry is 0

      

+2


source







All Articles