问题
I'm having trouble trying to compare an element to all elements of a set. I want to write a boolean function that returns true if an element is not a neighbour and false if an element is a neighbour. We want to colour the chart so that two countries that share a border are not given the same colour. I will explain it with code
type Country = string;;
type Chart = Set<Country*Country>;;
type Colour = Set<Country>;;
type Colouring = Set<Colour>;;
(* This is how you tell that two countries are neighbours. It requires a chart.*)
let areNeighbours ct1 ct2 chart =
Set.contains (ct1,ct2) chart || Set.contains (ct2,ct1) chart;;
(* val areNeighbours :
ct1:'a -> ct2:'a -> chart:Set<'a * 'a> -> bool when 'a : comparison
*)
I'm having trouble with the canBeExtBy function. If this is my chart and my col:
val myWorld : Chart =
set
[("Andorra", "Benin"); ("Andorra", "Canada"); ("Andorra", "Denmark");
("Benin", "Canada"); ("Benin", "Denmark"); ("Canada", "Denmark");
("Estonia", "Canada"); ("Estonia", "Denmark"); ("Estonia", "Finland");
...]
col = set
["Canada"]
then my function should return false if I call
canBeExtBy col "Denmark" myWorld;;
Here is my code, I get an error which is listed at the bottom.
(* The colour col can be extended by the country ct when they are no neighbours
according to chart.*)
val canBeExtBy :
col:Set<'a> -> ct:'a -> chart:Set<'a * 'a> -> bool when 'a : comparison
*)
Error:
Set.forall(fun x -> areNeighbours x ct) col;;
----------------------^^^^^^^^^^^^^^^^^^
This expression was expected to have type
bool
but here has type
Set<'a * 'a> -> bool
回答1:
Listen to your types.
This expression was expected to have type
bool
but here has type
Set<'a * 'a> -> bool
Instead of a boolean value, there is a function of type Set<'a * 'b> -> bool
. That is a sign for a partially applied function that's missing its last argument of type Set<'a * 'b>
. If you look at your areNeighbours
function, you can see that it takes three arguments, two of type Country
, and one of type Chart
, but in canBeExtBy
, you're only passing it two Country
values, but not the Chart
.
To make it compile, canBeExtBy
needs to look like this:
let canBeExtBy col ct chart =
Set.forall(fun x -> areNeighbours x ct chart |> not) col
来源:https://stackoverflow.com/questions/35399564/trouble-with-set-forall-f