在Haskell中修改了"break"? [英] Modified `break` in Haskell?

查看:42
本文介绍了在Haskell中修改了"break"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

break 具有签名 [a]->(a-> Bool)->([a],[a]),据我所知,第一个元组等于 takeWhile谓词为真.第二元组是负责使谓词为假的项以及其余列表.

break has signature [a] -> (a -> Bool) -> ([a], [a]) where the first tuple equals, as I understand, takeWhile predicate is true. The second-tuple is the item responsible for making the predicate false plus the remaining list.

> break (== ' ') "hey there bro"
("hey"," there bro")

但是,是否有一个功能可以跳过负责破坏的项目?

But, is there a function that will skip the item responsible for breaking?

>foo? (== ' ') "hey there bro"
("hey","there bro")

推荐答案

不在标准库中,但是您可以使用 Functor 实例对

Not in the standard libraries, but you can conveniently drop 1 on the second element of the tuple using the Functor instance for pairs:

break (== ' ') "hey there bro"
== ("hey"," there bro")

drop 1 <$> break (== ' ') "hey there bro"
== ("hey","there bro")

< $> fmap 的中缀同义词.使用 drop 1 代替 tail 处理空后缀的情况:

<$> is an infix synonym for fmap. Using drop 1 instead of tail handles the case of an empty suffix:

drop 1 <$> break (== ' ') "hey"
== ("hey","")

tail <$> break (== ' ') "hey"
== ("hey","*** Exception: Prelude.tail: empty list

但是,当使用元组时,我通常更喜欢使用 Control.Arrow 中的 second 而不是 fmap ,因为它传达了意图更好一点:

When working with tuples, though, I generally prefer to use second from Control.Arrow over fmap, because it conveys the intent a bit better:

second (drop 1) $ break (== ' ') "hey there bro"
== ("hey","there bro")

这篇关于在Haskell中修改了"break"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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