我正在用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 ->
发布于 2017-04-21 15:24:10
标准的技巧是将计数器作为附加参数传递。
对于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
https://stackoverflow.com/questions/43546314
复制相似问题