Fortran

Guide To Learn

Exercise 2: Reversing an array

The solution to this exercise has only two steps and you can write it as a single-line function (not counting the declaration code). First, we know that since we’re just reversing the order of elements, the resulting array will always be of the same size as the input array. The size will also correspond to the end index of the array. Second, once we know the size, we can slice the input from last to first and use the negative stride to go backward. The following listing provides the full code.

Listing 5.18 Reversing an input array

pure function reverse(x)
  real, intent(in) :: x(:)     ❶
  real :: reverse(size(x))     ❷
  reverse = x(size(x):1:-1)    ❸
end function reverse

❶ Assumed-shape array–no need for allocatable!

❷ The result will be the same size as the input.

❸ Slice with negative stride to reverse order

Notice that our input array doesn’t need to be declared allocatable. This is the so-called assumed-shape array, which takes whatever size array is passed by the caller. We can use the information about the size directly when declaring the result array.

You may be wondering why we’d make this a separate function at all when we can just do x(size(x):1:-1) to reverse any array. There are two advantages to making this a dedicated reverse function. First, if you need to reverse an array more than a few times, the one-liner slicing syntax soon becomes unwieldy. Every time you read it, there’s an extra step in the thought process to understand the intention behind the syntax. Second, the slicing syntax is allowed only when referencing an array variable, and you can’t use it on expressions, array constructors, or function results. In contrast, you can pass any of those as an argument to reverse. This is why we can make a test like all(x == reverse(reverse(x))). Try it!

I use this function in our stock-prices app, so if you’ve cloned the repo from GitHub, you can find it in src/mod_arrays.f 90.

Exercise 2: Reversing an array

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top