F# recursive function alternating between plus and minus

Viewed 115

I'm asked to remove one clause in below F# function, while maintaining it's functionality, that's alternating between plus and minus.

let rec altsum =
    function
    | [] -> 0
    | [ x ] -> x
    | x0 :: x1 :: xr -> x0 - x1 + altsum xr

I stumbled upon below solution, but I don't quite understand how it evaluates to the correct result since it only contain a minus symbol and not a plus symbol. Can someone please explain how below function altsum1 evaluates?

let rec altsum1 =
    function
    | [] -> 0
    | x0 :: xr -> x0 - altsum1 xr
1 Answers

It works because -1 * -1 = 1. We can then use the distributive property to show that:

a - (b - c) = a - b + c

So:

altsum([1; 2; 3; 4]) =
1 - altsum([2; 3; 4]) =
1 - (2 - altsum([3; 4])) =
1 - (2 - (3 - altsum[4])) =
1 - (2 - (3 - 4)) =
1 - 2 + 3 - 4 =
-2
Related