(filter procedure list)appliesprocedureto each element oflistand returns a new list containing only the elements for whichprocedurereturns true.
(R. Kent Dybvig The Scheme Programming Language) (online)
What may not be apparent from this description is that, while the elements in the returned
list occur in the same order as in list, the order of calls of procedure is not
specified in R6RS. (Racket, however, applies the procedure "to each element from first to last")
A recently active answer
mentions that it requires a filterfunc which works over its argument list
in order. How should one write this function?
An answer with my explanation of the issue is supplied.
What order might a Scheme implementation use, and why? Let's try it (all code run in Chez Scheme REPL):
R6RS implementations must check that
listis a proper listfilterin Chez Scheme which checks these requirements while filtering, resulting in the "452301" order of predicate applications, can be seen here(lines 589-617: a version is included as a spoiler below as an alternative to scrolling through the source on github)
The Chez Scheme code uses a "tortoise and hare" algorithm to detect cycles. Without error checks the code could be:
(the identifier
fastis used to match the Chez Scheme code: could belsotherwise)pred?"from first to last"?restvariable with an accumulator (compare the following with 3 above; the changes are small, but filtered elements areconsed to acc, so it has to be reversed to give the result):So 4 could be used as the required
filterfunc. It would be an interesting exercise to add error checks like the Chez Scheme implementation, which is effectively: