【问题标题】:SML: Error: non-constructor applied to argument in pattern: -SML:错误:非构造函数应用于模式中的参数:-
【发布时间】:2018-06-15 09:01:17
【问题描述】:

我正在为 MOOC 编写这个函数。它的工作是从list 中删除string 并返回没有字符串的列表作为SOME 或返回NONE 是字符串不存在。 我编写了下面的代码,但每当我尝试运行它时,都会出现以下错误:Error: non-constructor applied to argument in pattern: -

exception NotFound

fun all_except_option (str : string, strs : string list) =
    let
        fun remove_str (strs : string list) =
            case strs of
                []          => raise NotFound
              | str'::strs' => if same_string(str, str') then strs' else str'::remove_str strs'
    in
        SOME (remove_str strs) handle NotFound => NONE
    end

在哪里运行它的一项测试:

val test01-01 = all_except_option ("string", ["string"]) = SOME []

编辑

忘记包含为简化类型而提供给我们的 same_string 函数

fun same_string(s1 : string, s2 : string) =
    s1 = s2

【问题讨论】:

    标签: sml smlnj


    【解决方案1】:

    找出问题所在。好像SML 不喜欢连字符,就像我在测试中使用的那样:

    val test01-01 = all_except_option ("string", ["string"]) = SOME []

    我改为下划线,现在它可以工作了。

    val test01_01 = all_except_option ("string", ["string"]) = SOME []

    【讨论】:

      【解决方案2】:

      既然你已经解决了这个任务,下面是一种不使用异常的编写方法:

      fun all_except_option (_, []) = NONE
        | all_except_option (t, s :: ss) =
            if s = t
            then SOME ss (* don't include s in result, and don't recurse further *)
            else case all_except_option (t, ss) of
                      SOME ss' => SOME (s :: ss')
                    | NONE     => NONE
      

      让递归函数返回 t 选项 而不是 t 使其更难处理,因为在每次递归调用时,您必须检查它是否返回 SOME ...NONE。这可能意味着 很多 case ... of ... s!

      可以使用库函数Option.map 将它们抽象出来。该定义在the standard library 中找到并翻译为:

      fun (*Option.*)map f opt =
          case opt of
               SOME v => SOME (f v)
             | NONE   => NONE
      

      这一点类似于all_except_option 中的case ... of ...;重写它看起来像:

      fun all_except_option (_, []) = NONE
        | all_except_option (t, s :: ss) =
            if s = t
            then SOME ss (* don't include s in result, and don't recurse further *)
            else Option.map (fn ss' => s :: ss') (all_except_option (t, ss))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-30
        • 2013-12-13
        • 1970-01-01
        • 2020-03-16
        • 2012-09-02
        • 1970-01-01
        • 2021-12-31
        相关资源
        最近更新 更多