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

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

问题描述

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

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.

修订列表并获取高清是唯一的方法吗?谢谢.

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天全站免登陆