next up previous contents index
Next: Merge Up: Programming Concepts Previous: Best and rest   Contents   Index

Subsections

Sum

Description

The sum concept returns the sum of values which have been extracted from a list of data structures. It uses a foreach to scan each elements of the list and a fromto to accumulate the total sum.

Parameters

L
a list
Sum
a free variable, will be bound to a value

Schema

:-mode sum(+,-).
sum(L,Sum):-
        (foreach(X,L),
         fromto(0,In,Out,Sum) do
            q(X,V),
            Out is In+V
        ).

Comments

The initial value for the sum accumulator here is 0. We could use another initial value, this can be useful if we want to obtain the total over several summations.

Example

The program counts how many entries in the interface_mib_data list refer to active interfaces (octet count non-zero).
:-mode non_zero_measurements(+,-).
non_zero_measurements(L,N):-
        (foreach(X,L),
         fromto(0,In,Out,N) do
            non_zero_measurement(X,In,Out)
        ).

non_zero_measurement(interface_mib_data with [octet_in:A,
                                              octet_out:B],
                     In,Out):-
        A+B > 0,
        !,
        Out is In+1.
non_zero_measurement(_X,In,In).


Warwick Harvey
2004-08-07