function - 我用 Set.Fold F# 做错了什么

标签 function f# functional-programming set

着色问题:

您好,我正在尝试实现一个 bool 函数,当颜色可以扩展到一个国家/地区时,该函数返回 true,否则返回 false,但我在使用集合时遇到问题,因为我们无法对它们进行模式匹配...

我的代码:

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 neghbours.  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
  *)

(* The colour col can be extended by the country ct when they are no neighbours
according to chart.*)

let canBeExtBy (col:Colouring) (ct:Country) (chart:Chart) = col |> Set.fold (fun x -> (if (areNeighbours x ct chart) then true else false))

预期结果:我们需要根据图表中定义的邻域检查 ct 是否是该列中任何国家/地区的邻居(假设该列中有国家/地区)。 所以如果

chart = set
    [("Andorra", "Benin"); ("Andorra", "Canada"); ("Andorra", "Denmark");
     ("Benin", "Canada"); ("Benin", "Denmark"); ("Canada", "Denmark");
     ("Estonia", "Canada"); ("Estonia", "Denmark"); ("Estonia", "Finland");
     ...]

col = set 
    ["Andorra"]

然后,当 ct = "Benin"或 "Canada"或 "Denmark"等时,canBeExt 应返回 false... 由于安道尔与这些国家/地区共享边界,并且因此它们不能涂成与安多拉相同的颜色。

显然,我在 canBeExtBy 中有一个类型错误,因为我试图返回一个 bool 并且它期待 'a:Colouring。 我不知道如何实现它..

感谢您的帮助!

最佳答案

这个怎么样?

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

将名称更改为对我来说更有意义的名称。你可能不同意。

关于function - 我用 Set.Fold F# 做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35276324/

相关文章:

javascript - 为什么我的函数遇到return后会执行剩下的代码(return inside of two loops)

f# - Seq.iter vs for - 有什么区别?

generics - F# 内联函数 : instance member constraint fail

f# - 如何让 TypeProviders 在 Xamarin/Monodevelop 上工作

haskell - 忽略非字母数字字符和大小写的回文检查器 Haskell

python - 函数式编程 Python : smallest number divisible by each of the numbers 1 to 20

programming-languages - 为什么使用 Erlang 决定 "against"?

javascript - javascript 中的搜索功能出错

c++ - boost::any,变体,基于它们的数组调用函数

c - c中strtol中参数 'base'的意义是什么?