Combining Predicates in F#

前端 未结 4 1331
日久生厌
日久生厌 2021-02-18 17:44

Is there a standard way of logically combining predicates in F#? For example, let\'s say I have isCar x and isBlue x then I want something that gives m

4条回答
  •  孤城傲影
    2021-02-18 17:59

    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.

提交回复
热议问题