0

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
Brett Rowberry
  • 1,030
  • 8
  • 21
  • 1
    What you have is fine, apart from the `= true` bit, which is redundant. – kaefer Oct 18 '18 at 05:19
  • 1
    You could also simplify it by using [List.exists](https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/list.exists%5B't%5D-function-%5Bfsharp%5D), then you'll avoid Option.isSome. – hlo Oct 18 '18 at 06:29

1 Answers1

2

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
goric
  • 11,491
  • 7
  • 53
  • 69