j3-fortran / fortran_proposals

Proposals for the Fortran Standard Committee
175 stars 14 forks source link

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

Open w6ws opened 1 year ago

w6ws commented 1 year ago

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.

klausler commented 1 year ago

LOGICAL and derived types are not ordered.

w6ws commented 1 year ago

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)

certik commented 1 year ago

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

perazz commented 1 year ago

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