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

Tree @master (Download .tar.gz)

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

### `flatten` ###

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

`flatten` evaluates its first argument to obtain a list, then evaluates
to the list obtained by interpolating all elements into a single list.
By interpolating we mean that, if some element is itself a list, the
individual elements of that list will be present, in the same order, in
the corresponding position, in the resulting list, and that this process
is applied recursively to any elements in sublists which are themselves
sublists.

    |   (flatten ())
    = ()

    |   (flatten (list 1 2 3))
    = (1 2 3)

    |   (flatten (list 1 (list 2 3 4) 5))
    = (1 2 3 4 5)

    |   (flatten (list 1 (list 2 3 (list 4 4 4)) 5))
    = (1 2 3 4 4 4 5)

    |   (flatten (list 1 () 5))
    = (1 5)

'<<SPEC'

(define flatten (fun (li)
  (bind flatten-r (fun (self li acc)
    (if (empty? li)
      acc
      (if (list? (head li))
        (self self (tail li) (self self (head li) acc))
        (self self (tail li) (prepend (head li) acc)))))
    (reverse (flatten-r flatten-r li ())))))