It is possible to write this using recursion. Note that
count_present(p_1, p_2, ..., p_n, p_{n+1})
returns the value count_present(p_1, p_2, ..., p_n)
unless all p_1
, …, p_{n+1}
are present and .TRUE.
. In this latter case the result is n+1
. count_present(p_1)
returns 1
if p_1
is .TRUE.
, 0
otherwise.
recursive function count_present(p1, p2, p3, p4, p5, p6, p7, p8) result (res)
logical, intent(in) :: p1, p2, p3, p4, p5, p6, p7, p8
optional p2, p3, p4, p5, p6, p7, p8
integer res
if (PRESENT(p8)) then
res = count_present(p1, p2, p3, p4, p5, p6, p7)
if (res.eq.7.and.p8) res = res+1
else if (PRESENT(p7)) then
res = count_present(p1, p2, p3, p4, p5, p6)
if (res.eq.6.and.p7) res = res+1
else if (PRESENT(p6)) then
res = count_present(p1, p2, p3, p4, p5)
if (res.eq.5.and.p6) res = res+1
else if (PRESENT(p5)) then
res = count_present(p1, p2, p3, p4)
if (res.eq.4.and.p5) res = res+1
else if (PRESENT(p4)) then
res = count_present(p1, p2, p3)
if (res.eq.3.and.p4) res = res+1
else if (PRESENT(p3)) then
res = count_present(p1, p2)
if (res.eq.2.and.p3) res = res+1
else if (PRESENT(p2)) then
res = count_present(p1)
if (res.eq.1.and.p2) res = res+1
else
res = COUNT([p1])
end if
end function count_present
Is this a good idea? Well, that’s another question.
solved How to simplify this Fortran function?