【问题标题】:Error SML NJ-Operator and Operand don't agree错误 SML NJ-Operator 和 Operand 不同意
【发布时间】:2014-06-20 22:44:05
【问题描述】:

当我尝试编译我的 ML 程序时,我收到一条错误消息:“Operator and Operand don't agree”。

candidates.sml:78.8-78.40 Error: operator and operand don't agree [tycon mismatch]
operator domain: int * (int * 'Z * 'Y) list
operand:         int * (int * real) list
in expression:
tr (n,candidates)

我了解错误,但找不到解决方案。 我得到错误的代码部分是:

 fun agonas fileName = 
    let 
        fun tr(n,[])=[]
        |   tr(n,((a,b,c)::d))=((n-a+1),b,c)::(tr(n,d))
        val (n,l,candidates) = parse fileName
        val cand = tr(n,candidates)
    in
        my_solution(l,cand)
  end;

,其中候选人与以下部分相关:

fun parse file =
let
(* a function to read an integer from an input stream *)
    fun next_int input =
    Option.valOf (TextIO.scanStream (Int.scan StringCvt.DEC) input)
(* a function to read a real that spans till the end of line *)
    fun next_real input =
    Option.valOf (TextIO.inputLine input)
(* open input file and read the two integers in the first line *)
    val stream = TextIO.openIn file
    val n = next_int stream
    val l = next_int stream
val _ = TextIO.inputLine stream
(* a function to read the pair of integer & real in subsequent lines *)
    fun scanner 0 acc = acc
      | scanner i acc =
        let
            val d = next_int stream
            val (SOME v) = Real.fromString (next_real stream)
        in
            scanner (i - 1) ((d, v) :: acc)
        end
in
    (n, l,  rev(scanner n []))
end;

fun my_solution ( n , l ,candidates ) = [2 ,3 ,5 ,4 ,6]
fun agonas fileName = my_solution ( parse fileName )

如果您能找到错误,我将不胜感激。在此先感谢。

【问题讨论】:

    标签: ml


    【解决方案1】:

    问题在于parse 使用scanner 构建了一个对列表——(int * real) list——而tr 期望得到一个三元组列表——(int * 'Z * 'Y) list

    不知道tr 应该做什么,快速而肮脏的解决方法是改变

    tr(n,((a,b,c)::d))=((n-a+1),b,c)::(tr(n,d))
    

    进入

    tr(n,((a,b)::d))=((n-a+1),b)::(tr(n,d))
    

    但这可能是错误的解决方案 - 这取决于代码应该做什么。

    (有时它有助于自己明确地写出类型 - 甚至在编写代码之前 - 而不是依靠类型推断来捕捉需要做更多思考的地方。)

    【讨论】:

      【解决方案2】:

      错误消息说明了一切:违规行调用trans,这是一个需要两个参数的函数,第二个是三元组的列表。但是,您传递的是 pairs 列表(由您的 scanner 函数生成)。

      您没有向我们展示 trans 函数,因此我无法更具体地说明适当的修复方法。

      【讨论】:

      • 对不起,函数 tr 和函数 trans 是一样的。我现在编辑了。你能看到错误吗?谢谢你的时间。
      • 嗯,错误是我已经描述过的:你的parse/scanner 函数和你的tr 函数不同意candidates 列表的结构。如果不知道这段代码试图实现什么,很难说如何修复它。但对于初学者,您可以尝试从函数 tr 的元组中删除 c 组件。
      猜你喜欢
      • 1970-01-01
      • 2014-07-15
      • 2013-12-25
      • 2017-01-03
      • 2017-01-27
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 2010-10-23
      相关资源
      最近更新 更多