Home / Docs / Standard library / Prelude

filter

Release v0.4.0Edition 0.1 and later

A function of the prelude, in scope in every module. Edition 0.1 and later.

Edition 0.1

una
pub filter[T](xs: List[T], keep: fn(T) -> Bool) -> List[T]
  ensures result.len <= xs.len

The elements x of xs for which keep(x) is true, in the order of xs; keep is called from the first element to the last, at most once per element. In edition 0.2 and later it takes an effectful and failing keep, and stops at the first failure (spec/14 §1).

Edition 0.2 and later

una
pub filter[T](xs: List[T], keep: fn(T) -> Bool) -> List[T]
  ensures result.len <= xs.len
  uses of keep
  fails of keep

The elements x of xs for which keep(x) is true, in the order of xs; keep is called from the first element to the last, at most once per element. In edition 0.2 and later it takes an effectful and failing keep, and stops at the first failure (spec/14 §1).

In editions 0.2, 0.3, 0.4, 0.5. In edition 0.1: keep has no effects and cannot fail: the declaration has no uses of keep or fails of keep.

Parameters

Returns

List[T]: the elements x of xs for which keep(x) is true, in order; never more than xs.

Effects

Those of keep: it calls keep from the first element on, at most once per element, has the effects of keep, and stops at the first failure of keep, which becomes its own.

See also

first_where, map

Example

src/shop.unauna
module shop

--- The prices over ten dollars, in cents.
pub main() -> Unit
  uses @console: Console[print]
=
  let prices = [1999, 499, 2499]
  let expensive = prices.filter(keep: fn(p) -> p > 1000)
  let total = expensive.sum()
  @console.print("{expensive.len} over 1000, {total} in all")

una run . prints:

Output
2 over 1000, 4498 in all

Specification

Generated from the standard modules of una v0.4.0 (docs/std/listing.json, which is not part of the specification). The specification governs: spec/14 §1.