I have a two-part question that might brush on preferred habits, and whether I'm unnecessarily complicating a problem. I've been using .C and learned .Call to do the heavy lifting from R. I wanted to do a comparison with .Fortran, and so I've been learning it as I go. Therefore, my issue may be due to my limited Fortran knowledge.
There are several functions implemented in R that I'd like to translate to Fortran that are related to each other. Rather than hash out the details of the problem I've created a minimum synonymous example that's impractical but a good illustration.
I have two functions and two related subroutines to find the magnitude and squared-magnitude, which make the entirety of the file:
! Actual functions
real function sumofsquaresfun (x,y)
implicit none
real :: x,y
sumofsquaresfun=x*x+y*y
end function sumofsquaresfun
real function magnitudefun(x,y)
implicit none
real :: x,y,tmp
tmp=sumofsquaresfun(x,y)
magnitudefun=sqrt(tmp)
end function magnitudefun
! Wrappers for R accessibility since R requires subroutines
subroutine sumofsquares(x,y,answer)
implicit none
real :: x,y
real answer
answer=sumofsquaresfun(x,y)
end subroutine sumofsquares
subroutine magnitude(x,y,answer)
implicit none
real :: x,y
real answer
answer=magnitudefun(x,y)
end subroutine magnitude
Suppose that both subroutines are useful when I'm in R, so keeping the two separate is important.
When I try t compile using
R CMD SHLIB fortrancode.f95
I have several errors the same two types of errors:
Error: Return type mismatch of function 'sumofsquaresfun' at (1) (UNKNOWN/REAL(4))
Error: Function 'sumofsquaresfun' at (1) has no IMPLICIT type
etc.
My questions in order of importance:
- Even if feasible, is this the preferred approach to such a problem? Should I be using modules instead? I've seen this discussion (using a Fortran module in R?) and the related one by the same OP but don't know if involving modules is necessary/optimal.
- If what I am trying to do is the correct way, what causes these embarrassing errors?
- I like to use functions because that's what they're meant for, but am I being too much of a purist by creating the subroutine wrappers? Is it better style to just do away with them so I only have the two subroutines?
Many thanks!