Method filter()


Method filter

mixed filter(mixed arr, void|mixed fun, mixed ... extra)

Description

Filters the elements in arr through fun.

arr is treated as a set of elements to be filtered, as follows:

array
multiset
string

Each element is filtered with fun. The return value is of the same type as arr and it contains the elements that fun accepted. fun is applied in order to each element, and that order is retained between the kept elements.

If fun is an array, it should have the same length as arr. In this case, the elements in arr are kept where the corresponding positions in fun are nonzero. Otherwise fun is used as described below.

mapping

The values are filtered with fun, and the index/value pairs it accepts are kept in the returned mapping.

program

The program is treated as a mapping containing the identifiers that are indexable from it and their values.

object

If there is a lfun::cast method in the object, it's called to try to cast the object to an array, a mapping, or a multiset, in that order, which is then filtered as described above.

Unless something else is mentioned above, fun is used as filter like this:

function

fun is called for each element. It gets the current element as the first argument and extra as the rest. The element is kept if it returns true, otherwise it's filtered out.

object

The object is used as a function like above, i.e. the lfun::`() method in it is called.

multiset
mapping

fun is indexed with each element. The element is kept if the result is nonzero, otherwise it's filtered out.

"zero or left out"

Each element that is callable is called with extra as arguments. The element is kept if the result of the call is nonzero, otherwise it's filtered out. Elements that aren't callable are also filtered out.

string

Each element is indexed with the given string. If the result of that is zero then the element is filtered out, otherwise the result is called with extra as arguments. The element is kept if the return value is nonzero, otherwise it's filtered out.

This is typically used when arr is a collection of objects, and fun is the name of some predicate function in them.

Note

The function is never destructive on arr.

See also

map(), foreach()