如何获取列表中匹配指定条件的最后一个元素
问题描述
现有一个元素取值覆盖3-10区间的列表,需要从中取出大于5且小于11的最后一个数值,约定在GHCi(Haskell交互环境)中的函数调用形式如下:
*Main> greatestIndexInRange [3, 6, 7, 2, 5, 1, 0, 10, 2] 5 11
从调用形式可以看出,函数接收三个参数:待处理数值列表、区间下界、区间上界,筛选规则为值严格大于下界、严格小于上界。
实现方案
不需要做复杂的全列表索引遍历,直接基于Haskell原生列表操作就能实现,默认自带无匹配值的容错逻辑,不会抛出运行时错误:
返回匹配值的版本
greatestIndexInRange :: Ord a => [a] -> a -> a -> Maybe a greatestIndexInRange xs low high = traverseReverse xs where traverseReverse [] = Nothing traverseReverse (y:ys) = case traverseReverse ys of Just res -> Just res Nothing -> if y > low && y < high then Just y else Nothing
逻辑很简单:递归遍历到列表尾部后开始回溯判断,第一个命中条件的元素就是整个列表最后一个符合要求的值。对于给出的测试用例,符合条件的元素依次是6、7、10,最终返回Just 10。
返回匹配值索引的版本
从函数命名来看如果需要返回最后一个匹配值的索引(从0开始计数),只需要在遍历时同步记录位置即可:
greatestIndexInRange :: Ord a => [a] -> a -> a -> Maybe Int greatestIndexInRange xs low high = traverseWithIdx 0 xs where traverseWithIdx _ [] = Nothing traverseWithIdx idx (y:ys) = case traverseWithIdx (idx + 1) ys of Just resIdx -> Just resIdx Nothing -> if y > low && y < high then Just idx else Nothing
这个版本跑测试用例会返回Just 7,对应原列表中10所在的位置。
内容的提问来源于stack exchange,提问作者Roberto da Veen
相关产品推荐
相关产品推荐

