I'm doing a school project in OCaml and I have to use a maximum of terminal recursive call as possible when doing recursive calls, but I don't know how to do that with a counter even tho the pedagos think it's possible. Any help with this please?
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 ->
The standard trick is to pass the counter as an additional parameter.
This is a key bit of knowledge for FP programmers.
Here's a non-tail-recursive function for determining the length of a list:
let rec ntr_length list =
match list with
| [] -> 0
| _ :: tail -> 1 + ntr_length tail
Here is the tail-recursive transformation that uses an extra parameter:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.