你可以使用模式匹配来绑定列表的最后一个元素吗? [英] Can you use pattern matching to bind the last element of a list?
问题描述
由于有一种方法可以通过模式匹配来绑定列表的头部和尾部,我想知道是否可以使用模式匹配来绑定列表的最后一个元素?
前奏> :set -XViewPatterns
Prelude>让f(last - > x)= x * 2
Prelude> f [1,2,3]
6
请注意,尽管如此,所以你可能想为列表为空的情况添加一个模式,否则 last
会抛出异常。
Prelude> f []
***例外:Prelude.last:空列表
另请注意,这只是句法糖。与正常模式匹配不同,这是 O(n),因为您仍然访问单向链接列表的最后一个元素。如果您需要更高效的访问权限,请考虑使用不同的数据结构,例如 Data.Sequence
,它提供了 O(1)两端的访问权。
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?
Yes, you can, using the ViewPatterns
extension.
Prelude> :set -XViewPatterns
Prelude> let f (last -> x) = x*2
Prelude> f [1, 2, 3]
6
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
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屋!