Mark
Mark

Reputation: 1663

F# Bool list check if 1 element in the list true

I have a list of booleans and I want to check if 1 element in the list is true. The way my program works is whenever a boolean list is created it'll have only one true value or none at all.

Any ideas how I could go about this?

Upvotes: 2

Views: 2022

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564403

You can use List.contains to see if there is a true value within the list:

let containsTrue = theBoolList |> List.contains true

If you need to check for exactly one true value, you could fold over the list to count them:

let fn count item = if item then (count + 1) else count
let numberOfTrue = theBoolList |> List.fold fn 0

let onlyOneTrue = numberOfTrue = 1

Upvotes: 4

Related Questions