Delfino
Delfino

Reputation: 1009

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

Upvotes: 0

Views: 1201

Answers (2)

user2129306
user2129306

Reputation:

A solution using only the List.foldl function is the following.

fun altSum ls = if (List.foldl op+ 0 (map (fn x => 1) ls)) mod 2 = 0 
                then ~1 * (List.foldl (fn (x, y) => y - x) 0 ls)
                else List.foldl (fn (x, y) => y - x) 0 ls

You can see why this works here.

Upvotes: 1

newacct
newacct

Reputation: 122489

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

Upvotes: 3

Related Questions