How do you combine filter conditions

后端 未结 4 1497
悲哀的现实
悲哀的现实 2021-02-02 09:42

The filter class of functions takes a condition (a -> Bool) and applies it when filtering.

What is the best way to use a filter on when you have multiple conditions?

4条回答
  •  滥情空心
    2021-02-02 10:37

    Let's say your conditions are stored in a list called conditions. This list has the type [a -> Bool].

    To apply all conditions to a value x, you can use map:

    map ($ x) conditions
    

    This applies each condition to x and returns a list of Bool. To reduce this list into a single boolean, True if all elements are True, and False otherwise, you can use the and function:

    and $ map ($ x) conditions
    

    Now you have a function that combines all conditions. Let's give it a name:

    combined_condition x = and $ map ($ x) conditions
    

    This function has the type a -> Bool, so we can use it in a call to filter:

    filter combined_condition [1..10]
    

提交回复
热议问题