Skip to content

Instantly share code, notes, and snippets.

@shintakezou
Created April 14, 2019 16:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shintakezou/339a329c93eb11822befb68cce64abe9 to your computer and use it in GitHub Desktop.
Save shintakezou/339a329c93eb11822befb68cce64abe9 to your computer and use it in GitHub Desktop.
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
@MiCurry
Copy link

MiCurry commented Jan 22, 2021

Thanks for the example!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment