是否有一个简单的解决方案来接收元素* prior *并击中dropWhice谓词? [英] Is there a straight-forward solution to receiving the element *prior* to hitting the dropWhile predicate?

查看:86
本文介绍了是否有一个简单的解决方案来接收元素* prior *并击中dropWhice谓词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个条件,我想搜索一个元素列表,然后返回达到条件的第一个元素和前一个.

Given a condition, I want to search through a list of elements and return the first element that reaches the condition, and the previous one.

在C/C ++中,这很容易:

In C/C++ this is easy :

int i = 0;
for(;;i++) if (arr[i] == 0) break;

获得满足条件的索引后,通过"arr[i-1]"很容易获得上一个元素

After we get the index where the condition is met, getting the previous element is easy, through "arr[i-1]"

在Haskell中:

  • dropWhile (/=0) list给了我们我想要的最后一个元素

  • dropWhile (/=0) list gives us the last element I want

takeWhile (/=0) list为我们提供了我想要的第一个元素

takeWhile (/=0) list gives us the first element I want

但是我看不到以简单的方式同时获得两者的方法.我可以枚举列表并使用索引,但这似乎很麻烦.有没有适当的方法可以做到这一点,或者有解决此问题的方法?

But I don't see a way of getting both in a simple manner. I could enumerate the list and use indexing, but that seems messy. Is there a proper way of doing this, or a way of working around this?

推荐答案

我将列表尾部压缩,以便您拥有成对的元素 可用的.然后,您可以在配对列表中使用find:

I would zip the list with its tail so that you have pairs of elements available. Then you can just use find on the list of pairs:

f :: [Int] -> Maybe (Int, Int)
f xs = find ((>3) . snd) (zip xs (tail xs))

> f [1..10]
Just (3,4)

如果 first 元素与谓词匹配,则将返回 Nothing(如果有第二个匹配项,则为第二个匹配项),因此,如果您需要某些内容,可能需要特例 不同.

If the first element matches the predicate this will return Nothing (or the second match if there is one) so you might need to special-case that if you want something different.

罗宾·齐格蒙德(Robin Zigmond)所说的break也可以工作:

As Robin Zigmond says break can also work:

g :: [Int] -> (Int, Int)
g xs = case break (>3) xs of (_, []) -> error "not found"
                             ([], _) -> error "first element"
                             (ys, z:_) -> (last ys, z)

(或者根据您的需要,也返回Maybe.)

(Or have this return a Maybe as well, depending on what you need.)

但是,我认为这会将整个前缀ys保留在内存中直到 找到匹配项,而f可以开始垃圾收集元素 它已经过去了.对于小清单来说,没关系.

But this will, I think, keep the whole prefix ys in memory until it finds the match, whereas f can start garbage-collecting the elements it has moved past. For small lists it doesn't matter.

这篇关于是否有一个简单的解决方案来接收元素* prior *并击中dropWhice谓词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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