【问题标题】:Standard ML error:operator and operand don't agree标准 ML 错误:运算符和操作数不一致
【发布时间】:2016-08-05 03:11:00
【问题描述】:

我想编写一个函数number_before_reaching_sum,它接受一个名为 sum 的 int,并返回一个 int n,使得列表的前 n 个元素相加小于 sum,但列表的前 n + 1 个元素相加总和或更多。 这是我的代码

 fun number_before_reaching_sum(sum:int,lists:int list)=
 let
 val sum_list=0
 val n=0
 in
     let fun list_compute(sum_list:int,lists2:int list,n:int)=
           let val sum_list2=sum_list+(hd lists2)
           in if sum_list2>=sum
                  then (sum_list2,n+1)
              else (#1 list_compute(sum_list2,tl lists2,n+1),#2 list_compute(sum_list2,tl lists2,n+1))
               end
     in   #2 list_compute(sum_list,lists,n)
     end
 end

错误信息打印出来:

    hw1_1.sml:67.14-67.97 Error: operator and operand don't agree [type mismatch]
  operator domain: {1:'Y; 'Z}
  operand:         int * int list * int -> 'X
  in expression:
    (fn {1=1,...} => 1) list_compute
hw1_1.sml:67.14-67.97 Error: operator and operand don't agree [type mismatch]
  operator domain: {2:'Y; 'Z}
  operand:         int * int list * int -> 'X
  in expression:
    (fn {2=2,...} => 2) list_compute
hw1_1.sml:69.11-69.44 Error: operator and operand don't agree [type mismatch]
  operator domain: {2:'Y; 'Z}
  operand:         int * int list * int -> int * int
  in expression:
    (fn {2=2,...} => 2) list_compute

我不明白为什么(#1 list_compute(sum_list2,tl lists2,n+1),#2 list_compute(sum_list2,tl lists2,n+1))#2 list_compute(sum_list,lists,n) 这 2 行是错误的。

【问题讨论】:

  • 一般来说,如果您在标准 ML 中遇到这样的错误,那是因为您忘记将某些表达式括在括号中。

标签: sml


【解决方案1】:

f g(x,y) 被解析为 (f g) (x,y),而不是 f (g (x,y))。所以你想像这样添加括号:

#1 (list_compute (sum_list2,tl lists2,n+1))

否则它会尝试将#1 应用于函数list_compute。错误消息是编译器告诉你“#1 想要一个元组,但你给了它一个函数”。

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 2017-06-28
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 2017-12-12
    相关资源
    最近更新 更多