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

Tree @master (Download .tar.gz)

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

### `lookup` ###

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

`lookup` evaluates its first argument to a value of any type, and its
second argument to obtain an alist.  It then searches through the
pairs of the alist, looking for the first pair whose first element
is equal to the value.  If such a pair is found, it returns a
one-element list containing the second element of that pair.  If no
such pair is found, the empty list is returned.

    | (lookup (literal b) (literal ((a 1) (b 2) (c 3))))
    = (2)

    | (lookup (literal a) (literal ((a 1) (a 2) (a 3))))
    = (1)

    | (lookup (literal r) (literal ((a 1) (b 2) (c 3))))
    = ()

    | (lookup (literal q) ())
    = ()

    | (lookup (literal q) 55)
    ? abort (expected-list 55)

    | (lookup (literal q) (literal ((a 7) 99 (q 4))))
    ? abort (expected-list 99)

'<<SPEC'

(define lookup (fun (id alist)
  (bind lookup-r (fun (self id alist)
    (if (empty? alist)
      ()
      (if (equal? id (head (head alist)))
        (list (head (tail (head alist))))
        (self self id (tail alist)))))
    (lookup-r lookup-r id alist))))