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

Tree @master (Download .tar.gz)

find.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
-->

### `find` ###

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

`find` evaluates its first argument to obtain a predicate, then evaluates
its second argument to obtain a list.  It then evaluates to a list which
is either empty, if no element of the list satisfies the predicate, or
a list which contains exactly one element, which will be the first
element from the list which satisfies the predicate.

    |   (find (fun (x) (symbol? x)) ())
    = ()

    |   (find (fun (x) (symbol? x)) (list 1 2 3))
    = ()

    |   (find (fun (x) #t) (list 1 2 3))
    = (1)

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

`find` could be defined in terms of `filter`, but in practice it would
be implemented in a way which need not examine the entire list.

'<<SPEC'

(define find (fun (pred li)
  (bind find-r (fun (self pred li)
    (if (empty? li)
      ()
      (if (pred (head li))
        (list (head li))
        (self self pred (tail li)))))
    (find-r find-r pred li))))