Range Over Channels in Fortran

program range_over_channels
    use iso_fortran_env, only: int32
    implicit none

    ! We'll iterate over 2 values in the 'queue' channel.
    character(len=3), dimension(2) :: queue
    integer :: i

    queue(1) = "one"
    queue(2) = "two"

    ! This loop iterates over each element in 'queue'.
    ! In Fortran, we use a do loop to iterate over the array.
    do i = 1, size(queue)
        print *, queue(i)
    end do

end program range_over_channels

In this Fortran example, we’re demonstrating a concept similar to ranging over channels in other languages. However, Fortran doesn’t have built-in channel or coroutine concepts, so we’re using an array to simulate the behavior.

Here’s how the program works:

  1. We define an array queue to hold two string values.

  2. We populate the queue with the values “one” and “two”.

  3. We use a do loop to iterate over the elements of the queue array. This is analogous to the range-based iteration in the original example.

  4. Inside the loop, we print each element of the array.

To run the program, save it in a file with a .f90 extension (e.g., range_over_channels.f90) and compile it using a Fortran compiler:

$ gfortran range_over_channels.f90 -o range_over_channels
$ ./range_over_channels
 one
 two

This example demonstrates how to iterate over a collection of values in Fortran. While it doesn’t directly translate the concept of channels, it shows how you can achieve similar functionality using Fortran’s array and looping constructs.

Note that Fortran doesn’t have a direct equivalent to closing channels or the concept of receiving values from a channel. In Fortran, once an array is defined and populated, all its values are immediately available for processing.