Reduction in Java

 

Similarly,two ways are available if we wanted to reduce a list.

Wired-in versions of reduce, based on a binary function B and a unit U:

Recursive version of reduce:

static int reduce(intList L)
{
if( isEmpty(L) )
  return U;
return B(first(L), reduce(rest(L)));
}

 

Recursive version of reduce using accumulator:

This function would be called at the outset as

reduce(L, U)

i.e. U is the value of the accumulator in the outermost call

static int reduce(intList L, int Acc)
{
if( isEmpty(L) )
  return Acc;
return reduce(rest(L), B(Acc, first(L)));
}

 

Iterative version of reduce:

static int reduce(intList L)
{
int Acc = U;		// Unit
while( !isEmpty(L) )
  {
  Acc = B(Acc, first(L));
  L = rest(L);
  }
return Acc;
}

 

Next Slide Previous Slide Contents