|
| 1 | +#:include "common.fypp" |
| 2 | + |
| 3 | +#:set KINDS_TYPES = REAL_KINDS_TYPES + INT_KINDS_TYPES + CMPLX_KINDS_TYPES + & |
| 4 | + & [('l1','logical')] |
| 5 | + |
| 6 | +module stdlib_experimental_optval |
| 7 | + !! |
| 8 | + !! Provides a generic function `optval`, which can be used to |
| 9 | + !! conveniently implement fallback values for optional arguments |
| 10 | + !! to subprograms. If `x` is an `optional` parameter of a |
| 11 | + !! subprogram, then the expression `optval(x, default)` inside that |
| 12 | + !! subprogram evaluates to `x` if it is present, otherwise `default`. |
| 13 | + !! |
| 14 | + !! It is an error to call `optval` with a single actual argument. |
| 15 | + !! |
| 16 | + use stdlib_experimental_kinds, only: sp, dp, qp, int8, int16, int32, int64 |
| 17 | + implicit none |
| 18 | + |
| 19 | + |
| 20 | + private |
| 21 | + public :: optval |
| 22 | + |
| 23 | + |
| 24 | + interface optval |
| 25 | + #:for k1, t1 in KINDS_TYPES |
| 26 | + module procedure optval_${t1[0]}$${k1}$ |
| 27 | + #:endfor |
| 28 | + module procedure optval_character |
| 29 | + ! TODO: differentiate ascii & ucs char kinds |
| 30 | + end interface optval |
| 31 | + |
| 32 | + |
| 33 | +contains |
| 34 | + |
| 35 | + #:for k1, t1 in KINDS_TYPES |
| 36 | + pure elemental function optval_${t1[0]}$${k1}$(x, default) result(y) |
| 37 | + ${t1}$, intent(in), optional :: x |
| 38 | + ${t1}$, intent(in) :: default |
| 39 | + ${t1}$ :: y |
| 40 | + |
| 41 | + if (present(x)) then |
| 42 | + y = x |
| 43 | + else |
| 44 | + y = default |
| 45 | + end if |
| 46 | + end function optval_${t1[0]}$${k1}$ |
| 47 | + #:endfor |
| 48 | + |
| 49 | + ! Cannot be made elemental |
| 50 | + pure function optval_character(x, default) result(y) |
| 51 | + character(len=*), intent(in), optional :: x |
| 52 | + character(len=*), intent(in) :: default |
| 53 | + character(len=:), allocatable :: y |
| 54 | + |
| 55 | + if (present(x)) then |
| 56 | + y = x |
| 57 | + else |
| 58 | + y = default |
| 59 | + end if |
| 60 | + end function optval_character |
| 61 | + |
| 62 | +end module stdlib_experimental_optval |
0 commit comments