j3-fortran/fortran_proposals

Add optional keyword to FINDLOC to indicate the input is sorted.

Opened this issue · 4 comments

w6ws commented

If some sort of 'ordered=.true.' keyword were allowed in the FINDLOC intrinsic function, a binary search could be performed for improved performance.

Yes, I could easily roll my own - and have a number of times. And yes, I can use C Interop to call bsearch(3c) - which is a bit of a PITA due to needing to supply a comparison function. But it would be handy if FINDLOC just intrinsically supported the operation.

LOGICAL and derived types are not ordered.

w6ws commented

So state that when the option is specified, the input must have type real, integer, or character.

Derived types are not intrinsic types, so already not supported. For derived type arrays, one would use the desired component like:

type mine_t
character(32) :: name
end type

type (mine_t), allocatable :: mine_array(:)

integer :: i

! ... mine_array is loaded in sorted order by the 'name' field...

i = findloc (mine_array%name, value='xyzzy', ordered=.true., dim=1)

@w6ws in the meantime, you can contribute such routines into stdlib: https://github.com/fortran-lang/stdlib.

I don’t think this is a good idea for an intrinsic function: if the user prescribes ordered=.true. but the input data is not, it would return garbage/ invalid values in a non predictable way