【问题标题】:SML Types of rules don't agree and righthand side of clause doesn't agree with function result typeSML 规则类型不一致且子句右侧与函数结果类型不一致
【发布时间】:2021-10-16 18:09:54
【问题描述】:

我正在尝试用 sml 编写一个函数,该函数接受一个函数并将其应用于列表中的所有元素。如果任何元素返回 NONE,则整个函数 eval 为 NONE,但如果任何元素返回 SOME v,则该元素被添加到累加器中。

最终的返回值是累加器的一些。现在我遇到了两个错误。

  1. hw4.sml:93.21-95.67 错误:规则类型不一致 [tycon mismatch] 较早的规则:'Z 选项 -> 'Y 选项 这条规则:'Z 选项 -> 'X 列表 在规则: 一些 v => ((all_answers_helper ) xs') v @ acc
  2. hw4.sml:90.5-95.67 错误:子句右侧与函数结果类型不符 [tycon mismatch]
    表达式:'Z 列表 -> 'Y 列表 -> 'Y 列表选项 结果类型:'Z 列表 -> 'Y 列表 -> 'Y 列表 在声明中: all_answers_helper = (fn arg => (fn => ))
fun all_answers_helper f xs acc = 
        case xs of 
        [] => SOME acc
        | x::xs' => case f x of 
                    NONE => NONE
                    | SOME v => all_answers_helper f xs' v @ acc

但我不知道我做错了什么。感谢所有帮助!

【问题讨论】:

    标签: sml smlnj


    【解决方案1】:

    看起来你被运算符优先级绊倒了。前缀函数和构造函数应用程序(“普通的”,如SOME)比中缀应用程序绑定得更紧密。所以当你写all_answers_helper f xs' v @ acc(all_answers_helper f xs' v) @ acc一样——all_answers_helper的应用比@的绑定更紧密。

    您可以改用all_answers_helper f xs' (v @ acc) 来解决此问题。请注意,这意味着v 本身就是一个列表。根据您对将“元素”添加到累加器的描述,您可能指的是all_answers_helper f xs' (v :: acc),即只是将元素添加到而不是将两个列表附加在一起。

    【讨论】:

      【解决方案2】:

      我认为@kopecs 有它,但您可能还会发现在函数签名中使用模式匹配来使您的代码更容易推理很有用。

      fun all_answers_helper _ [] acc = SOME acc
        | all_answers_helper f (x::xs) acc = 
            case f x of 
                NONE => NONE
              | SOME v => all_answers_helper f xs (v :: acc)
      

      了解运算符优先级对于避免编程错误至关重要,但您也可以通过引入本地绑定来回避这一点。

      fun all_answers_helper _ [] acc = SOME acc
        | all_answers_helper f (x::xs) acc = 
            case f x of 
                NONE => NONE
              | SOME v => 
                   let 
                     val updated_acc = v :: acc
                   in
                     all_answers_helper f xs updated_acc
                   end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-27
        相关资源
        最近更新 更多