Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Nested functions in Fortran (2003, 2008…)
module counter2
implicit none
type element
character(len=16) :: s
integer :: e1, e2
end type element
contains
function count_unique(s) result(c)
implicit none
integer :: c
type(element), dimension(:), intent(in) :: s
integer :: i, j
logical :: found
c = 0
do i = 1, size(s)
found = .false.
do j = 1, i-1
if (comp(i, j) == 0) then
found = .true.
exit
end if
end do
if (.not. found) c = c + 1
end do
contains
function comp(i, j) result(d)
implicit none
integer :: d
integer, intent(in) :: i, j
if (s(i)%e2 == s(j)%e2) then
d = 0
else if (s(i)%e1 /= s(j)%e1) then
d = s(j)%e1 - s(i)%e1
else
d = s(j)%e2 - s(i)%e2
end if
end function comp
end function count_unique
end module counter2
program local2
use counter2
implicit none
integer :: i
type(element), dimension(4) :: s = [ &
element("zak", 2, 0), &
element("mac", 3, 1), &
element("abc", 4, 2), &
element("zak", 5, 0) ]
print *, count_unique(s)
do i = 1, size(s)
print *, "<" // trim(s(i)%s) // ">"
end do
end program local2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.