Range Over Channels in Scheme
In a previous example, we saw how to iterate over basic data structures. We can also use similar syntax to iterate over values received from a channel-like structure in Scheme.
(use-modules (ice-9 q))
(define (main)
; We'll iterate over 2 values in the 'queue' channel.
(let ((queue (make-q)))
(enq! queue "one")
(enq! queue "two")
; This iteration goes through each element as it's
; received from 'queue'. Because we empty the queue
; during iteration, it terminates after receiving the 2 elements.
(let loop ()
(if (not (q-empty? queue))
(begin
(display (deq! queue))
(newline)
(loop))))))
(main)
This example demonstrates how to create a queue-like structure in Scheme and iterate over its elements. Here’s a breakdown of what’s happening:
We use the
(ice-9 q)
module, which provides queue operations in Scheme.We create a queue using
(make-q)
and add two elements to it usingenq!
.We then use a recursive function (
loop
) to iterate over the queue elements. This is similar to the range iteration in the original example.We check if the queue is not empty using
q-empty?
. If it’s not empty, we remove and display an element usingdeq!
, then continue the loop.This process continues until the queue is empty, effectively iterating over all elements.
When you run this program, you should see the following output:
one
two
This example shows that it’s possible to iterate over a queue-like structure in Scheme, similar to ranging over a channel in other languages. The concept of closing a channel doesn’t directly apply in Scheme, but the iteration naturally terminates when the queue becomes empty.