Search code examples
.netf#functional-programmingcompositionfunction-composition

Validate input with any function in a list


Say I want to validate an input that has to satisfy one of a number of functions. What is the best way to do this in F#? Here’s a little example I came up with.

let funcs = 
            [
                fun x -> x % 2 = 0
                fun x -> x % 3 = 0
                fun x -> x % 5 = 0
            ]

let oneWorks x = funcs |> List.tryFind (fun f -> f x = true) |> Option.isSome

oneWorks 2 //true
oneWorks 3 //true
oneWorks 5 //true
oneWorks 7 //false

Solution

  • As the comments say, what you have will work fine.

    However, I would simplify it to:

    let any x = funcs |> Seq.exists (fun f -> f x)
    
    any 2 //true
    any 3 //true
    any 5 //true
    any 7 //false