如何获取与条件匹配的列表的最后一个元素?
因此,我有一个从3到10的数字列表。我想获得大于5和小于11的最后一个数字。
*Main> greatestIndexInRange [3, 6, 7, 2, 5, 1, 0, 10, 2] 5 11
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以
反向列表,
>通过您的谓词,然后选择结果列表的 /code> (这将是原始列表中的最后一个元素),以线性时间为单位。或者,您可以选择 /a>元素中的元素。
例如:
请注意,这是一个部分函数,如果列表中的列表中没有元素在给定范围内,例如:
正如克里斯在评论中所建议的那样,您也可以使用过滤+
HEAD
,以稍微优雅的实现:该功能现在返回
也许
。这也将解决以上问题的部分功能:You could
reverse
the list,filter
by your predicate and select the resulting list'shead
(which would be the last element in the original list) in linear time. Or you could select thelast
element in the filtered list.For example:
Note that this is a partial function that will fail if no element in the list is in the given range, e.g.:
As Chris suggested in the comments, you could also use
find
fromData.List
on the reversed list instead offilter
+head
for a slightly more elegant implementation:The function now returns a
Maybe
. This would also resolve the above issue of it being a partial function:您可能希望选择
过滤
使用上次
,而不是使用反向
与查找
。更好的解决方案取决于以下因素,例如:我们想要的元素列表中的位置,与列表中存在的谓词相匹配的元素等等。美好的!例如,如果我们想要的元素是一个开始时,则一定要逆转并使用
查找
比使用filter
与last
更糟糕。同样,如果我们有很多元素与
过滤器
的谓词(均匀分布在列表中分布),那么您将更好地反转列表并使用查找
。如果没有,则将您的结果包裹在中是明智的,以防万一没有。这个想法是您需要以某种方式进入列表的结尾。因此,无论哪种方式,除非订购列表,否则您将获得比线性时间更好的解决方案。
输出:
You may wish to choose using
filter
withlast
than usingreverse
withfind
. The better solution depends on factors such as: the location in the list of the element we want, how many elements that match our predicate exist in the list, etc. You might decide on a case-by-case basis, but either solution is fine!For instance, if the element we want is one and at the beginning, definitely reversing it and using
find
is worse than usingfilter
withlast
.Equally, if we have lots of elements that match our
filter
's predicate, uniformly distributed across the list, you will be better off reversing the list and usefind
.It would be wise to wrap your result in a
Maybe
in case there is none. The idea is that you need to get to the end of the list somehow. So either way, you will not get a better solution than linear time, unless the list is ordered in which case you could do a binary search.Output:
这将使您在GHC 9.2或更新中做您想做的事:
This will let you do what you want on GHC 9.2 or newer:
您可以使用以下简单实现。
另外,使用
foldr
而不是递归:我们记住在给定范围内的最后一个值,并将其替换为当前值(如果在给定范围内)。我们还考虑一个事实,即在给定范围内可能没有值。
You can use the following simple implementation.
Alternatively, using
foldr
instead of recursion:We remember the last value that is in the given range, and replace it with the current value if is in the given range. We also take into consideration the fact that there may not be a value in the given range.