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

Tree @master (Download .tar.gz)

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

### `fold` ###

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

`fold` evaluates its first argument to obtain an operator, generally assumed to
be a two-argument function, its second argument to obtain an initial value,
and its third argument to obtain a list.  It then applies the function to
successive elements of the list.  Each time the function is applied, an
element from the list is passed as the first argument.  The first time the
function is applied, the initial value is passed as the second argument;
each subsequent time, the result of the previous application is passed as
the second argument.  `fold` evaluates to the result of the the final
application of the function.

    | (fold (fun (x a) x) () (literal (three dog night)))
    = night

    | (fold (fun (x a) a) 541 (literal (archie moffam)))
    = 541

    | (fold (fun (x a) (list a x)) () (literal (three dog night)))
    = (((() three) dog) night)

    | (fold 99 (fun (x a) a) (literal (three dog night)))
    ? abort (inapplicable-object 99)

'<<SPEC'

;(requires empty?)
(define fold (fun (app acc li)
  (bind fold-r (fun (self app acc li)
    (if (empty? li)
      acc
      (self self app (app (head li) acc) (tail li))))
    (fold-r fold-r app acc li))))