Guest User

Untitled

a guest
Apr 26th, 2018
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. let findi x l =
  2. let rec loop i n l =
  3. match l with
  4. | y::tl -> loop (i+1) (if y = x then i else n) tl
  5. | [] -> n
  6. in
  7. loop 0 (-1) l;;
  8.  
  9. let rindex elem =
  10. let rec find_index i max_found = function
  11. | (x::xs) when x = elem -> find_index (i+1) i xs
  12. | (_::xs) -> find_index (i+1) max_found xs
  13. | [] -> max_found
  14. in find_index 0 (-1);;
  15.  
  16. let rindex elem ls =
  17. let find_index (i, max) elem' = (i+1, if elem' = elem then i else max)
  18. in snd (fold_left find_index (0, -1) ls);;
  19.  
  20. let find_index elt lst =
  21. (* Wrap inner function that accepts an accumulator to keep the interface clean *)
  22. let rec find_it elt acc = function
  23. | hd :: tl when elt = hd -> acc (* match *)
  24. | hd :: tl -> find_it elt (acc + 1) tl (* non-match *)
  25. | _ -> raise Not_found (* end of list *)
  26. in find_it elt 0 lst (* call inner function with accumulator starting at 0 *)
  27. ;;
Add Comment
Please, Sign In to add comment