Categories
Tech

F# Friday — The exists Function

The collections modules in F# all define an exists function that takes a predicate and an instance of the collection. If any item in the collection meets the predicate, exists returns true. Otherwise, it returns false.

[1..12] |> List.exists (fun n -> n = 11)
// val it : bool = true

[|1..12|] |> Array.exists (fun n -> n < 1)
// val it : bool = false

set [1..12] |> Set.exists (fun n -> n % 2 = 0)
// val it : bool = true

seq [1..12] |> Seq.exists (fun n -> n > 20)
// val it : bool = false

Of course, as lists, arrays, and sets are all sequences, we can use Seq.exists for all of them:

[1..12] |> Seq.exists (fun n -> n = 11)
// val it : bool = true

[|1..12|] |> Seq.exists (fun n -> n < 1)
// val it : bool = false

set [1..12] |> Seq.exists (fun n -> n % 2 = 0)
// val it : bool = true

Strings are collections/sequences of characters, so both of the following are valid:

"asdf" |> String.exists (fun c -> c = 's')
// val it : bool = true

"asdf" |> Seq.exists (fun c -> c = 'b')
// val it : bool = false

The Map module also defines an exists function, but the predicate takes two inputs: one for the key and one for the value.

[("A", 1); ("B", 2); ("C", 4); ("D", 8)]
|> Map.ofList
|> Map.exists (fun k v -> (k,v) = ("C",4))
// val it : bool = true

And of course, if you want to test only the key or only the value, name the input of no interest with an underscore in the lambda.

[("A", 1); ("B", 2); ("C", 4); ("D", 8)]
|> Map.ofList
|> Map.exists (fun k _ -> k = "Z")
// val it : bool = false

[("A", 1); ("B", 2); ("C", 4); ("D", 8)]
|> Map.ofList
|> Map.exists (fun _ v -> v = 2)
// val it : bool = true

The Option module also defines an exists function. If the option is Some, then exists applies the predicate to the value in the Some instance and returns the result. If the option is None, then exists always returns false.

Some "X" |> Option.exists (fun s -> s = "X")
// val it : bool = true

Some "X" |> Option.exists (fun s -> s = "Y")
// val it : bool = false

None |> Option.exists (fun s -> s = "X")
// val it : bool = false

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.