Applications of reduce intrinsic?

To understand how the Fortran 2018 reduce intrinsic works I wrote a short code showing how it can duplicate sum and product given functions to add and multiply two variables. What are some practical applications of reduce?

module pure_binary_funcs_mod
implicit none
contains
pure function add(i,j) result(sum_ij)
integer, intent(in) :: i, j
integer             :: sum_ij
sum_ij = i + j
end function add
!
pure function mult(i,j) result(prod_ij)
integer, intent(in) :: i, j
integer             :: prod_ij
prod_ij = i*j
end function mult
end module pure_binary_funcs_mod

program test_reduce ! works with Intel Fortran, not yet gfortran
use pure_binary_funcs_mod
implicit none
integer, parameter :: n = 3, vec(n) = [2, 5, 10], &
         mat(n,2) = reshape([vec,2*vec],shape=[size(vec),2])
logical, parameter :: keep(size(vec)) = [.true., .false., .true.]
print*,mat(:,1) ! 2  5 10
print*,mat(:,2) ! 4 10 20
! In lines below the two expressions give the same results.
! reduce applied to vec(:)
print*,reduce(vec,add),sum(vec) ! 17
print*,reduce(vec,mult),product(vec) ! 100
print*,reduce(vec,add,mask=keep),sum(vec,mask=keep) ! 12
print*,reduce(vec,mult,mask=keep),product(vec,mask=keep) ! 20
! reduce applied to mat(:,:)
print*,reduce(mat,add),sum(mat) ! 51
print*,reduce(mat,mult),product(mat) ! 80000
print*,reduce(mat,add,dim=1),sum(mat,dim=1) ! 17 34
print*,reduce(mat,mult,dim=1),product(mat,dim=1) ! 100 800
print*,reduce(mat,add,dim=2),sum(mat,dim=2) ! 6 15 30
end program test_reduce

Links to some resources:

Edit: something similar is available in C++

4 Likes