ocaml中带有计数器的终端递归调用

Terminal recursive call with counter in ocaml

我正在用 OCaml 做一个学校项目,在进行递归调用时我必须尽可能多地使用终端递归调用,但我不知道如何用计数器做到这一点,即使教师认为这是可能的。请问有什么帮助吗?

 let getContactId cl f p = match cl with
    | []                                        -> exit -1
    | (fn, ln, age, mail, tel)::tl when f = All -> if p = fn || p = ln || p = age || p = mail || p = tel then 0 else 1 + getContactId tl f p
    | (fn, _, _, _, _)::tl when f = Firstname   -> if p = fn then 0 else 1 + getContactId tl f p 
    | (_, ln, _, _, _)::tl when f = Lastname    -> if p = ln then 0 else 1 + getContactId tl f p
    | (_, _, age, _, _)::tl when f = Age        -> if p = age then 0 else 1 + getContactId tl f p
    | (_, _, _, mail, _)::tl when f = Email     -> if p = mail then 0 else 1 + getContactId tl f p
    | (_, _, _, _, tel)::tl when f = Phone      -> if p = tel then 0 else 1 + getContactId tl f p
    | (_, _, _, _, _)::tl when f = Id           -> 

标准技巧是将计数器作为附加参数传递。

这是 FP 程序员的关键知识点。

这是一个用于确定列表长度的非尾递归函数:

let rec ntr_length list =
    match list with
    | [] -> 0
    | _ :: tail -> 1 + ntr_length tail

这是使用额外参数的尾递归转换:

let tr_length list =
    let rec i_length accum list =
        match list with
        | [] -> accum
        | _ :: tail -> i_length (accum + 1) tail
    in
    i_length 0 list