Im having trouble getting a function, that has to be recursive, to take a character and and return an integer array as result.
My example code:
program main
implicit none
integer :: i
integer, dimension(3) :: myresult, rec_fun
character(1) :: input
input = 'B'
myresult = rec_fun(input)
do i = 1,3
write(*,*) myresult(i)
end do
end program main
recursive function rec_fun(input) result(a)
implicit none
character(1), intent(in) :: input
integer, dimension(3) :: a
if (input == 'A') then
a(1) = 2
a(2) = 3
a(3) = 4
return
else
a = rec_fun('A') * 2
return
end if
end function rec_fun
The function rec_fun is supposed to take a character and give back an integer array. The output of the write loop in the main program should therefore be: 4 6 8
What does work is (integer -> integer), (character -> integer) and also (integer dimension(3) -> integer dimension(3)), which means the argument/return types dont need to be equal. However I need (character -> integer dimension(3)). But somehow taking a character and returning an array is not accepted and when trying to compile (gcc compiler with flag -lgfortran) I get
"Error: Array index at (1) must be of INTEGER type, found CHARACTER"
with (1) pointing to the first use of the function name in the main program in line 8. I don't know how to fix this is a way that is scalable and not hard coded, so that I could replace 3 with 1 Million. Workarounds using pointers etc won't work either, because array operations will be applied directly to the functions output on return. Does anyone have any ideas? Thanks.
EDIT: I find this question to be different, because it looks at the problem of array return and recursion within one function, plus neither of the suggested questions use the keyword "interface" in their solutions.
My solution, using an explicit interface, as suggested in the comments:
program main
implicit none
interface
recursive function rec_fun(input) result(a)
character(1), intent(in) :: input
integer, dimension(3) :: a
end function rec_fun
end interface
integer :: i
integer, dimension(3) :: myresult
character(1) :: input
input = 'B'
myresult = rec_fun(input)
do i = 1,3
write(*,*) myresult(i)
end do
end program main
It compiles now and prints the correct results. However I'm not sure about how legit this solution is, since I never used fortran interfaces before.