f# - How to find index of last element in list matching predicate? -
i last index of element in list matching predicate. know can use following code array, wondering if there way list (without converting array , using below function):
let tryfindlastindex f (arr: 'a []) = let rec loop n (arr: 'a []) = match n | -1 -> none | n -> if f arr.[n] n else loop (n-1) arr loop (arr.length - 1) arr
list
in f# linked list can't iterate in last->first direction. because of have iterate beginning , keep track of both current index , index of last element matches predicate.
you still use local recursive function that.
let tryfindlastindex f source = let rec loop index lastfoundindex source = let newindex = index+1 match source | [] -> lastfoundindex | head :: tail -> if f head loop newindex (some index) tail else loop newindex lastfoundindex tail loop 0 none source
Comments
Post a Comment