Wafl Home

List Tutorial

Function aggregate

The sum of list elements is a representative of a very often kind of list processing:

sumList(l) =
    if empty(l) then 0
    else l->hd() + l->tl()->sumList();

Elements are processed one by one to compute the single result. The principle is often called aggregation or reduction.

Wafl library includes functions aggregate(l,f,z) and leftAggregate(l,f,z), which abstract such list processing in different directions. Function aggregate assumes right associativity, while function leftAggregate assumes left associativity. Because the list structure implies right associativity (remember, list [1,2,3] is equivalent to 1:2:3:[], where : is right associative) aggregate is the one that processes lists in natural direction.

The expression aggregate([1,2,3],operator+,0) is equivalent to 1 + (2 + (3 + 0)), while leftAggregate([1,2,3],operator+,0) is equivalent to ((0 + 1) + 2) + 3.

The appropriate function types are:

aggregate :     (List['1] * ('1 * '2 -> '2) * '2 -> '2)
leftAggregate : (List['1] * ('2 * '1 -> '2) * '2 -> '2)

The types differ in the type of functional argument. In the case of aggregate, the first argument of the function is of list element type, and the second is of result type. In the case of leftAggregate the opposite stands.

Applications aggregate(l,f,z) and leftAggregate(l,f,z) are equivalent if f is (1) associative for any arguments and (2) z is zero for f (i.e. f(x,z)=f(z,x)=x for any x).

Source code:

{#
// sumList([1,2,3])
[1,2,3]->aggregate(operator+,0),
['1','2','3']->aggregate(operator+,''),
[1,2,3]->aggregate(\x,l: x:l,[]),
[1,2,3]->leftAggregate(\l,x: x:l,[]),
[1,2,3]->append([4,5,6]),
[[1],[2],[3]]->appendLists()
#}
where{
    append( l1, l2 ) = 
        aggregate( l1, operator:, l2 );
    appendLists(l) =
        aggregate( l, append, [] );
}

Result:

{# 6, "123", [1,2,3], [3,2,1], [1,2,3,4,5,6], [1,2,3] #}

 

Table of Contents

Let's Start

Program Structure

Primitive Data Types

List

Tuple

Record

HTML

Command Line Interpreter

Using Web Servers

Syntax

Examples

Tips

The most of examples evaluates with both command line and Web server Wafl interpreters. If any example is based on specific features of an interpreter, it is explicitly annotated.