I am solving the following problem:
You are given two lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a list.
I wrote the following code:
let addTwoNumbers (a: int list) (b: int list) =
let rec loop (a: int list) (b: int list) (c: int list) (carry: int) =
match a, b, carry with
| (h1::t1), (h2::t2), _ ->
let q, r = Math.DivRem(h1 + h2 + carry, 10)
loop t1 t2 (List.append c [r]) q
| (h1::t1), [], _ ->
let q, r = Math.DivRem(h1 + carry, 10)
loop t1 [] (List.append c [r]) q
| [], (h2::t2), _ ->
let q, r = Math.DivRem(h2 + carry, 10)
loop [] t2 (List.append c [r]) q
| [], [], 0 ->
c
| [], [], carry ->
let q, r = Math.DivRem(carry, 10)
loop [] [] (List.append c [r]) q
loop a b [] 0
Is there a way to simplify and possibly to de-duplicate some of this code?