【问题标题】:Trouble with Set.forall F#Set.forall F# 的问题
【发布时间】:2016-02-14 23:59:13
【问题描述】:

我在尝试将一个元素与集合中的所有元素进行比较时遇到问题。我想编写一个布尔函数,如果元素不是邻居则返回 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 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
  *)

我在使用 canBeExtBy 函数时遇到问题。如果这是我的图表和我的 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"]

如果我调用,我的函数应该返回 false

canBeExtBy col "Denmark" myWorld;;

这是我的代码,我收到一个错误,列在底部。

(* 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
    *)

错误:

 Set.forall(fun x -> areNeighbours x ct) col;;
  ----------------------^^^^^^^^^^^^^^^^^^
This expression was expected to have type
    bool    
but here has type
    Set<'a * 'a> -> bool  

【问题讨论】:

  • 您的 areNeighbours 函数需要三个参数,但您在 lambda 中只传递了两个(xct)。
  • @TeaDrivenDev 您应该将此作为答案发布:)
  • 出于好奇,您是 McGill 的 CS 学生吗?

标签: f#


【解决方案1】:

听你的类型。

This expression was expected to have type
    bool    
but here has type
    Set<'a * 'a> -> bool

有一个Set&lt;'a * 'b&gt; -&gt; bool 类型的函数,而不是布尔值。这是一个部分应用函数的标志,该函数缺少其最后一个 Set&lt;'a * 'b&gt; 类型的参数。如果您查看areNeighbours 函数,您会发现它需要三个参数,两个Country 类型和一个Chart 类型,但在canBeExtBy 中,您只传递了两个Country值,但不是 Chart

要使其编译,canBeExtBy 需要如下所示:

let canBeExtBy col ct chart =
    Set.forall(fun x -> areNeighbours x ct chart |> not) col

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多