在过滤器函数中用逻辑&&连接谓词

Chr*_*raf 2 haskell

我刚刚在learnyouahaskell.com 上偶然发现了这句话:

在列表推导式中应用多个谓词的过滤器等效于多次过滤某些内容或将谓词与逻辑 && 函数连接起来。

有人可以为最后一部分(将谓词与逻辑 && 函数连接起来)举个例子吗?

作者的意思是这样的吗(不起作用):

filter ((>3) && (<10)) [5,3]
Run Code Online (Sandbox Code Playgroud)

luq*_*qui 5

filter's predicate argument is a function, so you would need to use a lambda:

filter (\x -> x > 3 && x < 10) [5,3]
Run Code Online (Sandbox Code Playgroud)

I suppose the author was assuming the reader would do the appropriate expansion.

It's also possible to lift boolean operators to operate on predicates using the (a ->) Applicative instance:

filter (liftA2 (&&) (> 3) (< 10)) [5,3]
Run Code Online (Sandbox Code Playgroud)

But I don't personally find that particularly nice.

  • @ChrisGraf如果您在过滤器 inRange [5,3] 中使用 let inRange x = x &gt; 3 &amp;&amp; x &lt; 10 ,则不需要 lambda 。这使用了本书使用的样式,仅在您引用的部分上方几行。 (2认同)