PPP Exercises: Reduce Operator


  1. Implement the following function
         reduce(A, B, C <:Ok  i :Iter.T(A)
                apply(:A) :B
                accumulate(:B :C) :C
                base :C) :C
    
    'reduce' applies the function 'apply' to each element of the iteration 'i'. Then 'accumulate' is applied to the intermediate result of the latter operation and to the accumulation of all previous intermediate results. The initial intermediate result is 'base'. In case of an empty iteration 'i' this is also the result of the function. In case of a non-empty 'i' a call to 'accumulate' will yield the final result of 'reduce'.

  2. Implement the following functions using the previous 'reduce' with the right primitives for 'apply', 'accumulate' and 'base'.
      
    forEach(E <:Ok  i :Iter.T(E)  statement(:E) :Ok) :Ok
    (* Executes for all elements of i the function 'statement'. *)
       
    map(E, F <:Ok  i :Iter.T(E)  f(:E) :F) :Iter.T(F)
    (* Returns an iteration over the results of function 'f'
       applied to each element of 'i'. *)
    
    select(E <:Ok  i :Iter.T(E)  p(:E) :Bool) :Iter.T(E)
    (* Returns an iteration over the elements of 'i'
       that fulfill predicate 'p'. *)
    
    maximum(E <:Ok  i :Iter.T(E)  greater(:E :E) :Bool) :E
    (* Returns the "maximum" element of 'i' with respect to
       comparisons by 'greater' *)
            
    sum(E, V <:Ok   i :Iter.T(E)  getValue(:E) :V
        zero :V  addValues(:V :V) :V) :V
    (* No comment! *)
    

Ulrike Steffens, 1994