

Prior to Fortran 2018, you had to specify the attribute recursive if the function was to be used recursively. Say you have a recursive function, an ubiquitous textbook example being the Fibonacci function: pure recursive integer function fibonacci(n) result(fib) integer, intent(in) :: n if (n = 0) then fib = 0 else if (n = 1) then fib = 1 else fib = fibonacci(n-1) + fibonacci(n-2) end if end function fibonacci This is why I made map available as part of functional-fortran. If you wanted to apply a recursive function to an array, you had to resort to a do-loop. However, elemental originally came with a restriction - you couldn’t make a procedure both elemental and recursive. I’ve never used more than 5 dimensions myself but I’m sure there are application domains that make good use many-dimensional arrays. Fortran supports up to 15-dimensional arrays. Further, you can apply square to an array of any rank. Without any modifications to the code, you can apply square to an array - square() returns. However, the elemental attribute makes this function surprisingly powerful. A minimal, though not terribly useful example, is: pure elemental real function square(x) real, intent(in) :: x square = x**2 end function square However, Fortran has had similar functionality built into the language since the Fortran 90 standard - elemental procedures.Įlemental procedures allow you to define a procedure that can operate both on a scalars and arrays at the same time.


On first look, Fortran doesn’t have anything like map in its standard library. This expression returns an array of same size as x. Given function f and array x, the typical syntax is map(f, x). This higher-order function applies a function f for each element in array x and returns the resulting array. Reduce, often also called fold, applies a reduction operation to an array and returns a scalar result.įortran 2018 now offers (almost) out-of-the-box support for map, filter, and reduce patterns. Filter applies a function to an array and returns only those elements that meet the criteria defined in the function. Map applies a function element-wise to an arbitrary array. Map, filter, and reduce are the core tools of a functional programmer - they allow you to solve problems by chaining recursive functions instead of piling do-loops and if-blocks one on top of another. John Backus, the original creator of FORTRAN at IBM in 1956, argued for functional programming in his 1977 Turing award lecture. While not a purely functional language, Fortran allows the programmer to express themselves functionally.
