Colouring problem :
Hello, I\'m trying to implement a bool function that returns true when a color can be extended to a country and false otherwise but I\'m having troub
What about this?
type Country = string
type Neighbours = Set<Country*Country>
type SharesColour = Set<Country>
let areNeighbours (ns : Neighbours) (ct1 : Country) (ct2 : Country) : bool =
Set.contains (ct1,ct2) ns || Set.contains (ct2,ct1) ns
let canShareColour (ns : Neighbours) (ct : Country) (s : SharesColour) : bool =
s |> Seq.exists (areNeighbours ns ct) |> not
let neighbours : Neighbours =
set [|
("Andorra", "Benin") ; ("Andorra", "Canada") ; ("Andorra", "Denmark");
("Benin" , "Canada") ; ("Benin" , "Denmark"); ("Canada" , "Denmark");
("Estonia", "Canada") ; ("Estonia", "Denmark"); ("Estonia", "Finland");
|]
let sharesColour : SharesColour =
set [|
"Andorra"
|]
[<EntryPoint>]
let main argv =
printfn "%A" <| canShareColour neighbours "Estonia" sharesColour
printfn "%A" <| canShareColour neighbours "Benin" sharesColour
0
Changed the names to something that made more sense to me. You might not agree.
To check that no element in a collection satisfies a given condition: that's not a job for fold
, but, with appropriate negation, for exists
or forall
.
Either of
let fornone f = Set.forall (f >> not)
let doesnotexist f = Set.exists f >> not
will do, as shown in the answer of FuleSnabel. However, it is certainly possible to build these functions from a fold
, albeit nobody would do that except as an illustration of currying, function composition and pointfree style.
let fornone f = Set.fold (fun s -> f >> not >> (&&) s) true
let doesnotexist f = Set.fold (fun s -> f >> (||) s) false >> not