I find named argument a great feature of Fortran. It really makes a difference when working with functions/subroutines with many arguments. By contrast, C and C++ don’t have it. Surprisingly, one of my friends who has used Fortran for more than 30 years doesn’t know this feature.
I tweeted about positional arguments.
You can force the user to use positional arguments by making the first argument optional with a type that is private, as shown below. I wonder if I should tweet about this or if it’s overly tricky and bad style.
module m
implicit none
private
public :: sd
type :: phony
end type phony
contains
function sd(phony_arg,x,mean) result(xsd)
type(phony), intent(in), optional :: phony_arg
real , intent(in) :: x(:)
real , intent(in) :: mean
real :: xsd
integer :: n
n = size(x)
xsd = sqrt(sum((x-mean)**2)/(n-1))
end function sd
end module m
!
program main
use m
implicit none
integer, parameter :: n = 10**6
real :: x(n)
call random_number(x)
print*,sd(x=x,mean=sum(x)/n)
end program main
The issue with the phony argument is that it might not be immediately evident what the caller did wrong from the compiler error message.
Recently, I bumped into an issue where I had to use named arguments. Consider the subroutine
subroutine dl_optimize_dense(optimum, p, nmeas, f, fparams, ctx)
real(wp), intent(out) :: optimum
real(wp), intent(inout), contiguous :: p(:)
integer, intent(in) :: nmeas
procedure(dl_callback_dense) :: f
class(*), intent(in), target, optional :: fparams
type(dl_solver_context_t), intent(out), optional :: ctx
Since fparams
is an unlimited polymorphic object you can pass anything in its place. It’s easy to mistakenly pass the ctx
object in place of fparams
. The solution is to use a named argument:
call dl_optimize_dense(opt, p, nmeas, f, &
ctx = context)
I also like named arguments very much Re C++, there seem to be many proposals up to now but rejected for various reasons…
These pages show some “workaround(s)”, but it seems a bit awkward to me… (compared to usual named arguments)
https://pdimov.github.io/blog/2020/09/07/named-parameters-in-c20/
https://rosettacode.org/wiki/Named_parameters#C.2B.2B
Recent discussion in C++ community: