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

Tree @master (Download .tar.gz)

index.robin @masterraw · history · blame

;'<<SPEC'

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

`index` evaluates its first argument to a natural number, and its
second argument to a list.  It then evaluates to the element of the
list at the index given by the natural number.  The index is 0-based;
0 refers to the element at the head of the list.

    |   (index 0 (literal (the girl from ipanema)))
    = the

    |   (index 2 (literal (the girl from ipanema)))
    = from

    |   (bind last (fun (li) (index (subtract (length li) 1) li))
    |     (last (literal (the girl from ipanema))))
    = ipanema

Attempting to index beyond the end of the list will produce an
abort value.

    |   (index 7 (literal (the girl from ipanema)))
    ? abort (expected-list ())

`index` expects its first argument to be a number.

    |   (index (literal goofy) (list 1 2 3 4 5))
    ? abort (expected-number goofy)

`index` expects its second argument to be a list.

    |   (index 8 (literal whatnot))
    ? abort (expected-list whatnot)

'<<SPEC'

(define index (fun (index li)
  (bind index-r (fun (self index li)
    (if (equal? index 0)
      (head li)
      (self self (subtract index 1) (tail li))))
  (index-r index-r index li))))