stepheba
stepheba

Reputation: 25

Create fortran function that can accept a scalar or an array

I am trying to write a function in fortran that takes two arguments, one of which will definitely be a 1-d array, but the other argument could be either an array or a scalar. This is similar to what one can do with the MIN or MAX intrinsic fortran functions, which could compare either two arrays, or a scalar and an array (MIN or MAX could include more arguments, but I just need two). I've been looking around online quite a bit but surprisingly I haven't found anything quite like this. Is this possible to do in Fortran? If I try to declare the incoming arguments with dimension(:) the compiler just expects them both to be 1-d arrays and it complains in case of a scalar argument.

Upvotes: 0

Views: 380

Answers (1)

evets
evets

Reputation: 1026

You can achieve what you want by writing an generic interface that encapsulates the two functions. Here's an example

module foo

  implicit none    ! Never write a module without this statement

  private          ! Never write a module without this statement

  public fcn       ! Make the generic function fcn public

  interface fcn    ! Define generic function
     module procedure bar
     module procedure bah
  end interface fcn

  contains
     ! Function accepts an array and a scalar
     function bar(a,b) result(res)
        integer res
        integer, intent(in) :: a(:)
        integer, intent(in) :: b
        res = sum(a * b)
     end function bar
     ! Function accepts to arrays
     function bah(a,b) result(res)
        integer res
        integer, intent(in) :: a(:)
        integer, intent(in) :: b(:)
        res = sum(a * b)
     end function bah
end module foo

program testing
  use foo
  implicit none
  integer i(4), j(4), k
  i = [1, 2, 3, 4]
  j = [10, 20, 30, 40]
  k = 10
  print *, fcn(i,k)
  print *, fcn(i,j)
end program testing

Upvotes: 3

Related Questions