模式匹配 SML?

Pattern Matching SML?

谁能解释一下:"description of g"? f1 如何使用 unit 和 returns 一个 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 if ps 形式的值,并且 vs 具有相同的长度并且对于所有 i,第 i 个ps 的元素匹配 vs 的第 i 个元素。生成的绑定列表是附加在一起的嵌套模式匹配的所有列表。

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

没有其他匹配项。

Can someone please explain the: "description of g"? How can f1 takes unit and returns an int & the rest i'm confused about too!!

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

  • 参数 f1f2 必须是始终 return 相同常量的确定性函数,或者具有 side-effects 的函数可以 return 一个任意整数/字符串,分别由外部来源确定。

    由于评论提到“每个通配符和变量 return 的编号 ”,f1 听起来更有可能return 不同时间的不同数字(我不确定 数字 f2 的情况下指的是什么!)。一种定义可能是这样的:

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

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

  • 评论将g的return值描述为

    [...] the sum of all those numbers for all the patterns wrapped in p.

    由于数字没有任何意义,因此 g 似乎没有任何实际用途,而是比较任意给定的一组 f1 和 [=14= 的输出] 针对未给出的任意测试。

  • Catch-all 模式通常是错误的:

      ...
    | _ => 0
    

    Nothing else matches.

    原因是如果你用额外类型的模式扩展pattern,编译器不会通知你函数g中缺少模式; catch-all 将错误地暗示可能尚未定义的情况的含义。