列表最后一个元素的值 [英] Value of the last element of a list

查看:38
本文介绍了列表最后一个元素的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取List的最后一个元素的值?我注意到 List.hd(或 .Head)返回一个项目,而 List.tl(或 .Tail)返回一个列表.

how to get the value of the last element of a List? I've noted that List.hd (or .Head) return an item, while List.tl (or .Tail) returns a List.

rev the List 和获取 hd 是唯一的方法吗?谢谢.

Is rev the List and get the hd the only way around? Thanks.

推荐答案

试试这个功能.它使用递归,但无论如何它都会针对迭代进行优化,因为它是尾递归.无论如何,这很可能比反转整个列表(使用 List.rev)更快.

Try this function. It uses recursion, though it gets optimised to iteration anyway since it's tail recursion. In any case, it is most likely quicker than reversing the entire list (using List.rev).

let rec last = function
    | hd :: [] -> hd
    | hd :: tl -> last tl
    | _ -> failwith "Empty list."

不过,Pavel Minaev 的回答绝对值得考虑.尽管如此,您请求的算法在某些极少数情况下可能很有用,并且是完成任务的最有效方法.

The answer of Pavel Minaev is definitely worth taking into account, however. Nonetheless, the algorithm you have requested may be useful in some rare cases, and is the most efficient way to go about the task.

这篇关于列表最后一个元素的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆