Fortran: Type-bound Procedures
In the previous post we defined a derived type point_t
with real
data components x
and y
, to represent a point in 2D space. We also wrote a function to calculate the distance between two such points:
module geometry
implicit none(type, external)
private
public :: point_t
public :: distance
type :: point_t
real :: x
real :: y
end type point_t
contains
pure function distance(point_1, point_2) result(the_distance)
type(point_t), intent(in) :: point_1
type(point_t), intent(in) :: point_2
real :: the_distance
the_distance = sqrt((point_2%x - point_1%x)**2 + &
(point_2%y - point_1%y)**2)
end function distance
end module geometry
This allowed us to pass point_t
instances as function arguments to distance
, in another module or in the program
:
By Matthias Noback
read moreFortran: Derived Types
We’ve seen types and variables and functions and subroutines. Now we can get to the next level and combine both variables and procedures in a so-called derived type.
Declaring a derived type and its data components
Object-oriented programming languages have classes. It took me some time to understand that classes can be seen as “extensions of the type system”. There are often primitive types like strings, integers, etc. and we can group them as properties of a class. Thereby, the class becomes some kind of advanced, composite type.
By Matthias Noback
read moreFortran: Functions and Subroutines
So far we’ve put code inside the main program
block of our application. Soon the need arises to move blocks of code to a better place: a procedure with a proper name living inside a module
which groups related procedures by topic.
Fortran has two types of procedures:
- Functions, with arguments and a return value
- Subroutines, which are functions without a return value
Subroutines
Let’s define a new subroutine in a module
:
By Matthias Noback
read moreFortran: Types and Variables
We’ve looked at the program
and module
blocks that can hold our code. Now we’ll find out where to put our data.
Declaration comes first
In Fortran, every time we want to store some value in a variable, we have to explicitly declare the type and the name of the variable first. This has to happen before any other executable statement, but after imports and other declarations like the implicit none
statement:
By Matthias Noback
read more