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:

  1. We use the (ice-9 q) module, which provides queue operations in Scheme.

  2. We create a queue using (make-q) and add two elements to it using enq!.

  3. We then use a recursive function (loop) to iterate over the queue elements. This is similar to the range iteration in the original example.

  4. We check if the queue is not empty using q-empty?. If it’s not empty, we remove and display an element using deq!, then continue the loop.

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