Recursive Data Structures in Fortran

I had the very same thought. Modern Fortran can do with continuous good advertisement and computations such as the Fibonacci sequence are nice, compact illustrators of other capabilities in Fortran such as with improved support starting Fortran 95 but ongoing with the current standard revision toward the functional programming paradigm e.g., all procedures are now recursive by default, elemental, etc.:

   print *, "32nd in Fibonacci sequence = ", fibonacci_number(32), "; expected is 2178309"
contains
   elemental integer function fibonacci_number( n ) result(num)
      integer, intent(in) :: n
      select case ( n ) 
         case ( 0:1 )
            num = n
         case default
            num = fibonacci_number(n-1) + fibonacci_number(n-2) 
      end select
   end function
end

C:\Temp>ifort /standard-semantics fibonacci.f90
Intel(R) Fortran Intel(R) 64 Compiler Classic for applications running on Intel(R) 64, Version 2021.3.0 Build 20210609_000000
Copyright (C) 1985-2021 Intel Corporation. All rights reserved.

Microsoft (R) Incremental Linker Version 14.29.30038.1
Copyright (C) Microsoft Corporation. All rights reserved.

-out:fibonacci.exe
-subsystem:console
fibonacci.obj

C:\Temp>fibonacci.exe
32nd in Fibonacci sequence = 2178309 ; expected is 2178309

C:\Temp>

When it comes to a tutorial toward recursive data structures in Fortran, my 2 cents is a more conventional example - say with a stack use case - will be apt.

1 Like