Next: Defining sequence types, Previous: Synchronous sequences, Up: Macros for writing loops
Gathering the indices of list elements that answer true to some predicate.
(define (select-matching-items list pred)
(reduce ((list* elt list)
(count* i 0))
((hits '()))
(if (pred elt)
(cons i hits)
hits)
(reverse hits)))
Finding the index of an element of a list that satisfies a predicate.
(define (find-matching-item list pred)
(iterate loop ((list* elt list)
(count* i 0))
() ; no state variables
(if (pred elt)
i
(loop))))
Reading one line of text from an input port.
(define (read-line port)
(iterate loop ((input* c port read-char))
((chars '()))
(if (char=? c #\newline)
(list->string (reverse chars))
(loop (cons c chars)))
(if (null? chars)
(eof-object) ; from the PRIMITIVES structure
(list->string (reverse chars)))))
Counting the lines in a file. This must be written in a way other than
with count* because it needs the value of the count after the
loop has finished, but the count variable would not be bound then.
(define (line-count filename)
(call-with-input-file filename
(lambda (inport)
(reduce ((input* line inport read-line))
((count 0))
(+ count 1)))))