【问题标题】:Pattern Matching SML?模式匹配 SML?
【发布时间】:2017-06-10 04:57:14
【问题描述】:

有人可以解释一下:“g 的描述”吗? f1 如何获取单位并返回一个 int 其余的我也很困惑!

(* Description of g:
 * g takes f1: unit -> int, f2: string -> int and p: pattern, and returns 
 * an int. f1 and f2 are used to specify what number to be returned for 
 * each Wildcard and Variable in p respectively. The return value is the 
 * sum of all those numbers for all the patterns wrapped in p.
 *)  

datatype pattern = Wildcard
                 | Variable of string
                 | UnitP
                 | ConstP of int
                 | TupleP of pattern list
                 | ConstructorP of string * pattern

datatype valu = Const of int
              | Unit
              | Tuple of valu list
              | Constructor of string * valu


fun g f1 f2 p =
    let
      val r = g f1 f2
    in
      case p of
           Wildcard           => f1 ()
         | Variable x         => f2 x
         | TupleP ps          => List.foldl (fn (p,i) => (r p) + i) 0 ps
         | ConstructorP (_,p) => r p
         | _                  => 0
    end

通配符匹配所有内容并生成空的绑定列表。

变量 s 匹配任何值 v 并生成包含 (s,v) 的单元素列表。

UnitP 仅匹配 Unit 并生成空的绑定列表。

ConstP 17 仅匹配 Const 17 并生成空的绑定列表(其他整数也类似)。

TupleP ps 匹配 Tuple vs 形式的值,如果 ps 和 vs 具有相同的长度并且对于所有 i,ps 的第 i 个元素匹配 vs 的第 i 个元素。生成的绑定列表是嵌套模式匹配中的所有列表附加在一起。

ConstructorP(s1,p) 匹配 Constructor(s2,v) 如果 s1 和 s2 是相同的字符串(你可以用 = 比较它们)并且 p 匹配 v。产生的绑定列表是嵌套模式匹配的列表。我们将字符串 s1 和 s2 称为构造函数名称。

没有其他匹配项。

【问题讨论】:

    标签: functional-programming sml ml


    【解决方案1】:

    有人可以解释一下:“g 的描述”吗? f1 如何获取单位并返回一个 int 其余的我也很困惑!

    • 函数g的类型为(unit → int) → (string → int) → pattern → int,所以它需要三个(curried)参数,其中两个是函数和一个是模式

    • 参数f1f2 必须是始终返回相同常量的确定性函数,或者是具有副作用的函数,可以分别返回由外部来源确定的任意整数/字符串。

      由于评论提到“每个通配符和变量要返回什么数字”,听起来f1 应该在不同的时间返回不同的数字(我不是确定 numberf2! 的情况下指的是什么)。一个定义可能是这样的:

      local
          val counter = ref 0
      in
          fun uniqueInt () = !counter before counter := !counter + 1
          fun uniqueString () = "s" ^ Int.toString (uniqueInt ())
      end
      

      虽然这只是一个猜测。此定义仅适用于 Int.maxInt

    • 评论将g的返回值描述为

      [...] 包含在 p 中的所有模式的所有这些数字的总和。

      由于这些数字没有任何意义,因此 g 似乎没有任何实际用途,而是将任意给定的 f1f2 集合的输出与任意测试进行比较t 给定的。

    • 包罗万象的模式通常很糟糕:

        ...
      | _ => 0
      

      没有其他匹配项。

      原因是,如果你用其他类型的模式扩展pattern,编译器不会在函数g 中通知你缺少模式;包罗万象将错误地暗示可能尚未定义的案例的含义。

    【讨论】:

    • 很好的答案!谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2021-06-01
    • 2012-09-02
    • 2013-01-14
    • 2014-09-30
    • 1970-01-01
    • 2018-10-05
    相关资源
    最近更新 更多