git @ Cat's Eye Technologies Robin / master stdlib / filter.robin
master

Tree @master (Download .tar.gz)

filter.robin @masterraw · history · blame

;'<<SPEC'

<!--
Copyright (c) 2012-2024, Chris Pressey, Cat's Eye Technologies.
This file is distributed under a 2-clause BSD license.  See LICENSES/ dir.
SPDX-License-Identifier: LicenseRef-BSD-2-Clause-X-Robin
-->

### `filter` ###

    -> Tests for functionality "Evaluate Robin Expression (with List)"

`filter` evaluates its first argument to obtain an operator, generally assumed
to be a predicate (a one-argument function which evaluates to a boolean).
It then evaluates its second argument to obtain a list.  It then evaluates
to a list which contains all the elements of the given list, in the same
order, which satisfy the predicate.

    |   (filter (fun (x) (symbol? x)) (literal (1 two #f 3 () four 5 six)))
    = (two four six)

    |   (filter (fun (x) x) (literal (#t #t #f banana #t #f)))
    ? abort (expected-boolean banana)

'<<SPEC'

(define filter (fun (pred li)
  (reverse (fold
    (fun (x acc) (if (pred x) (prepend x acc) acc))
    () li))))