Fortran 90: Overloaded Operators

Let's start this section out with an example. Define the data type vector, which is a double precision array of length 3.
type vector
   real*8 :: v(3)
end type vector
Put this definition in matvec.p for reference below.

Now we could make a function to add two vectors.

function vadd(v1,v2) result (v3)
   include "matvec.p"
   type (vector), intent(in) :: v1,v2
   type (vector),  :: v3
   v3%v = v1%v + v2%v ! Note the use of array operations
end function vadd
The following code will add two vectors
type (vector) a,b,c
a = vadd(b,c)
Now using operator overloading, we can call the vadd function by using "+".
interface operator (+)
   function vadd(v1,v2) result (v3)
      include "matvec.p"
      type (vector), intent(in) :: v1,v2
      type (vector),  :: v3
   end function vadd
end interface
Adding two vectors is now
type (vector) a,b,c
a = b + c
Let's define a function that takes two vectors and returns the dot product as a scalar.
function vdot(v1,v2) result (dot)
   include "matvec.p"
   type (vector), intent(in) :; v1,v2
   real*8 :: dot
   integer i
   dot = 0.0d0
   do i=1,3
      dot = dot + v1%v(i) * v2%v(i)
   enddo
Taking the dot product is then
type (vector) a,b
real*8 c
c = vdot(a,b)
Once again, operator overloading could be used to call this function with the "*" operator. Or if that may be confusing, we can define a new operator ".dot."
interface operator (*)   !   or (.dot.)
   function vdot(v1,v2) result (dot)
      include "matvec.p"
      type (vector), intent(in) :: v1,v2
      real*8 :: dot
   end function vdot
end function interface
Taking the dot product is now
type (vector) a,b
real*8 c
c = a*b  ! or c = a.dot.b
These examples could all be done more simply using the array intrinsics. But in cases where the array intrinsics are not sufficient, creating our own data types can be a powerfull tool.
Return to Fortran 90 index