Search code examples
listsmlfold

Alternating Sum Using FOLDR (SML)


I'm trying to use foldr to get an alternating sum from a list of int, but keep getting an operator/operand mismatch error. I have a feeling that I'm not completely understanding foldr

l = [1,3,5,7,9]
foldr (op-) l

I'm expecting to have the output be

1 - 3 + 5 - 7 + 9 = 5

EDIT:

I am actually being asked to use an anonymous function with foldr

So, for example

l = [1,3,5,7,9]
foldr (fn (x, y): => x - y) l

With the same expected output, but I'm still getting the same operand/operator mismatch


Solution

  • foldr (as well as foldl) take an initial value.

    The type of foldr is ('a * 'b -> 'b) -> 'b -> 'a list -> 'b, where 'b is the type of the result of each step in folding (as well as the initial value, which is the initial "result"); and 'a is the type of the elements in the list. Note that 'a and 'b can be different. The combining function takes an element and a previous result and returns the new result.

    Anyway, you need to think of an appropriate initial value. What should it be? I think 0 would do:

    foldr op- 0 l