多个元素的布尔运算符 [英] boolean operators over multiple elements

查看:95
本文介绍了多个元素的布尔运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道一个人可以做:

any (>3) [1,2,3,4,5]

但是实现的优雅方式是什么?

but what is the elegant way of implementing:

any and[(>3),(<5)] [1,2,3,4,5]

all or[(<2),(>4)] [1,2,3,4,5]

等吗?

推荐答案

我相信您想检查是否同时存在(<5)(>3)的任何元素.

I believe you'd like to check whether there are any elements that are both (<5) and (>3).

您可以这样操作:

any (\x -> x > 3 && x < 5) [1..5]

您的另一个可以通过

any (\x -> x < 2 || x > 4) [1..5]

但是定义&&||以便在函数上工作可能会更有趣:

But maybe it would be more fun to define && and || to work on functions:

infixr 3 &&&
infixr 3 |||

(&&&) :: (a -> Bool) -> (a -> Bool) -> (a -> Bool)
(f &&& g) x = f x && g x

(|||) :: (a -> Bool) -> (a -> Bool) -> (a -> Bool)
(f ||| g) x = f x || g x

所以现在我们可以将您的示例重写为:

so now we can rewrite your examples as:

any ((>3) &&& (<5)) [1..5]
any ((<2) ||| (>4)) [1..5]

这篇关于多个元素的布尔运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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