1

Is there a way to do something like the following in Fortran without having to do it explicitly for every dimension array?

Module OverloadTest
  interface arrayStuff
    module procedure :: arrayStuff_NxN, arrayStuff_2x2
  end interface

  contains

  function arrayStuff_NxN(A) result(output)

    real*8,dimension(:,:) :: A
    real*8, dimension(size(A,1), size(A,2)-1) :: output

    !code and stuff to populate output

  end function arrayStuff_NxN

  function arrayStuff_2x2(A) result(output)

    real*8,dimension(:,:) :: A
    real*8 :: output

    !code and stuff to populate output

  end function arrayStuff_2x2
End Module OverloadTest

To clarify I would like to be able to call arrayStuff function and if it is a 2x2 array I'd like it to pick the 2x2 and for all other sizes pick the NxN without having to specifically make a function for 3x3, 4x4, 5x5, ect.

TrippLamb
  • 1,422
  • 13
  • 24
  • One cannot have such a generic as `arrayStuff` where the argument `A` as here for each specific is an array which differs only in size/extent. Indeed the arguments here to the two functions are completely indistinguishable, both `real*8` assumed shape of rank 2. Function results do not disambiguate. – francescalus Oct 27 '15 at 01:01
  • Have you looked into generic interfaces? As @francescalus says they won't be able to help in this specific case, though. – Ross Oct 27 '15 at 01:03
  • I guess, you won't get around an if, write a wrapper routine, which calls the actual implementation internally based on the array size. The only other alternative I see is using function pointers. If you can decide the size of your array once, but need to call the function multiple times, you can set the function pointer appropriately and then go on calling it multiple times without the if evaluation every time. Not sure, what would yield better performance in your case, though. Is your question rather, how to achieve this kind of thing for arbitrary dimensionality? – haraldkl Oct 27 '15 at 03:00
  • See also this question and answer: http://stackoverflow.com/q/14434293/577108 – haraldkl Oct 27 '15 at 03:05
  • @haraldkl, I don't think I could use an if statement wrapper, since in one I return a 2d array and in the other I return a single value. The idea was a function to return the minor matrix for use in a recursive determinate function. I could return a 1x1 array but in the code that would make my answer an array which would be no better than just doing an if statement like I had previously. I would have thought it would default in this type of situation to the most specific function. – TrippLamb Oct 27 '15 at 15:03

1 Answers1

1

Not that I know of, because the (2, 2) shape would also match the (:, :) shape.

The best I could recommend was to only have the NxN function, and if it encounters a 2x2 array, pass that on to a special function.

Then, as output, put it into an size (1) array.

chw21
  • 7,970
  • 1
  • 16
  • 31