您可以使用模式匹配来绑定列表的最后一个元素吗? [英] Can you use pattern matching to bind the last element of a list?

查看:27
本文介绍了您可以使用模式匹配来绑定列表的最后一个元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

既然有一种方法可以通过模式匹配来绑定列表的头尾,我想知道是否可以使用模式匹配来绑定列表的最后一个元素?

Since there is a way to bind the head and tail of a list via pattern matching, I'm wondering if you can use pattern matching to bind the last element of a list?

推荐答案

是的,您可以使用 ViewPatterns 扩展.

Yes, you can, using the ViewPatterns extension.

Prelude> :set -XViewPatterns
Prelude> let f (last -> x) = x*2
Prelude> f [1, 2, 3]
6

请注意,此模式总是会成功,因此您可能希望为列表为空的情况添加模式,否则 last 将引发异常.

Note that this pattern will always succeed, though, so you'll probably want to add a pattern for the case where the list is empty, else last will throw an exception.

Prelude> f []
*** Exception: Prelude.last: empty list

另请注意,这只是语法糖.与普通模式匹配不同,这是O(n),因为您仍在访问单链表的最后一个元素.如果您需要更高效的访问,请考虑使用不同的数据结构,例如 Data.Sequence,它提供对两端的 O(1) 访问.

Also note that this is just syntactic sugar. Unlike normal pattern matching, this is O(n), since you're still accessing the last element of a singly-linked list. If you need more efficient access, consider using a different data structure such as Data.Sequence, which offers O(1) access to both ends.

这篇关于您可以使用模式匹配来绑定列表的最后一个元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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