Combining Predicates in F#

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-03 22:26:56

You could define a combinator.

let (<&>) f g = (fun x -> f x && g x)

then do

let isBlueCar = isCar <&> isBlue
let meetsAll preds = preds |> Seq.fold (fun p q x -> p x && q x) (fun _ -> true)
// or     let meetsAll preds x = preds |> Seq.forall (fun p -> p x)

as in

let isEven x = x%2 = 0
let isDiv5 x = x%5 = 0
let isDiv7 x = x%7 = 0

let div257 = meetsAll [isEven; isDiv5; isDiv7]

for i in 1..100 do
    if div257 i then
        printfn "%d" i

There is no standard library function for it, but there are a plethora of one-liners you can define on your own, as evidenced by the answers here.

You could do something like the following:

let predicates = [isCar; isBlue]
let isBlueCar x = predicates |> List.forall (fun predicate -> predicate x)

More generally:

let combinePredicates predicates =
    fun x -> predicates |> List.forall (fun predicate -> predicate x)

let isBlueCar = combinePredicates [isCar;isBlue]

Is this what you're looking for?

> let (&&<) a b x = a x && b x

val ( &&< ) : ('a -> bool) -> ('a -> bool) -> 'a -> bool

> let isBlueCar = isCar &&< isBlue

val isBlueCar : (int -> bool)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!