【问题标题】:How could I filter for many conditions in a list in Haskell?如何过滤 Haskell 列表中的许多条件?
【发布时间】:2019-12-14 08:29:06
【问题描述】:

函数定义已经给出

filterMany :: [a -> Bool] -> [a] -> [a]
filterMany (f:fs) [] = []
filterMany (f:fs) (x)
  | filter (f) x == True = x : filter (fs) x
  | otherwise = filter (fs) x

输出应该是:

filterMany [even, odd] [1..10] == []
filterMany [even, (\x -> x `mod` 4 /= 0)] [1..10] == [2,6,10]
filterMany [(<7), (>3), odd] [1..20] == [5]

【问题讨论】:

  • 这能回答你的问题吗? How do you combine filter conditions
  • 您应该递归调用filterMany,而不是filter。删除== True,它是多余的。 (variable) 中的括号也是多余的。
  • 你的意思是:filterMany' (f:fs) [] = [] filterMany' (f:fs) x | f x = x : filterMany' fs x |否则 = filterMany' fs x

标签: haskell


【解决方案1】:

您可以在这里使用all :: (a -&gt; Bool) -&gt; [a] -&gt; Bool 来检查是否满足所有条件。因此,我们可以通过以下方式实现:

filterMany :: Foldable f => f (a -> Bool) -> [a] -> [a]
filterMany fs = filter (\x -> all ($ x) fs)

因此,我们在这里通过指定all ($ x) fs 应用所有带有参数x 的谓词。如果所有这些谓词都成立,那么我们重新训练元素 x

例如:

Prelude> filterMany [even, odd] [1..10]
[]
Prelude> filterMany [even, (\x -> x `mod` 4 /= 0)] [1..10]
[2,6,10]
Prelude> filterMany [(<7), (>3), odd] [1..20]
[5]

【讨论】:

    【解决方案2】:

    另一种方式:

    filterMany :: [a -> Bool] -> [a] -> [a]
    filterMany [] (x:xs) = (x:xs)
    filterMany (f:fs) (x:xs) = filter f (filterMany (fs) (x:xs))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 2020-08-16
      • 2014-11-27
      • 2013-07-21
      • 1970-01-01
      相关资源
      最近更新 更多