假设l
是一个列表且elem
是一个元素,如何在列表elem
中返回元素l
的最后一次出现?如果元素在l
中不存在,也返回-1。我不太明白如何使用递归迭代列表...
let rec getLastOccurence l elem = …
答案 0 :(得分:3)
let findi x l =
let rec loop i n l =
match l with
| y::tl -> loop (i+1) (if y = x then i else n) tl
| [] -> n
in
loop 0 (-1) l;;
答案 1 :(得分:1)
基本上,您需要两个累加器来跟踪当前索引和元素的最大索引。然后你只需递归到列表的末尾并返回“最大索引”值。
let rindex elem =
let rec find_index i max_found = function
| (x::xs) when x = elem -> find_index (i+1) i xs
| (_::xs) -> find_index (i+1) max_found xs
| [] -> max_found
in find_index 0 (-1);;
这也可以简单地表达为折叠:
let rindex elem ls =
let find_index (i, max) elem' = (i+1, if elem' = elem then i else max)
in snd (fold_left find_index (0, -1) ls);;
答案 2 :(得分:0)
这是一种用于在列表中查找整数的尾递归算法:
let find_index elt lst =
(* Wrap inner function that accepts an accumulator to keep the interface clean *)
let rec find_it elt acc = function
| hd :: tl when elt = hd -> acc (* match *)
| hd :: tl -> find_it elt (acc + 1) tl (* non-match *)
| _ -> raise Not_found (* end of list *)
in find_it elt 0 lst (* call inner function with accumulator starting at 0 *)
;;