首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在ocaml中带有计数器的终端递归调用

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

Stack Overflow用户
提问于 2017-04-21 15:15:48
回答 1查看 535关注 0票数 0

我正在用OCaml做一个学校项目,在进行递归调用时,我必须尽可能地使用最大限度的终端递归调用,但是我不知道如何使用计数器,即使是老师认为有可能的计数器。能帮个忙吗?

代码语言:javascript
运行
复制
 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           -> 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-21 15:24:10

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

对于FP程序员来说,这是一个关键的知识点。

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

代码语言:javascript
运行
复制
let rec ntr_length list =
    match list with
    | [] -> 0
    | _ :: tail -> 1 + ntr_length tail

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

代码语言:javascript
运行
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43546314

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档