代码之家  ›  专栏  ›  技术社区  ›  Johannes Hoff

你能在小马模式匹配中解压值吗?

  •  1
  • Johannes Hoff  · 技术社区  · 6 年前

    Pony能够在类上进行模式匹配,还可以在匹配表达式中指定结果(使用 let ... : ),但是有没有一种方法可以解压匹配表达式中的值?比如像这样的事情?

    actor Main
      fun f(x: (Foo | Bar)): String =>
        match x
        | Foo(1) => "one"
        | Foo(2) => "two"
        | Foo(x) => x.string() // fails
        else
          "Bar"
        end
    

    我能想到的唯一选择就是

    actor Main
      fun f(x: (Foo | Bar)): String =>
        match x
        | Foo(1) => "one"
        | Foo(2) => "two"
        | Bar => "Bar"
        else
          try
            let f = x as Foo
            f.number.string()
          end
        end
    

    1 回复  |  直到 6 年前
        1
  •  2
  •   Florian Weimer    6 年前

    我假设你有这样的定义:

    class Foo is (Equatable[Foo box] & Stringable)
      var value: I32 = 1
      new create(value': I32) => value = value'
      fun box eq(other: Foo box): Bool => value == other.value
      fun string(): String iso^ => value.string()
    
    primitive Bar
    

    actor Main
      fun f(x: (Foo | Bar)): String =>
        match x
        | Foo(1) => "one"
        | Foo(2) => "two"
        | let x': Foo => x'.string()
        else
          "Bar"
        end
    

    我认为在这个特殊的情况下这不是太糟糕,但它肯定不是一个真正的解构绑定。Pony只支持这种形式的元组模式 (let first: First, let second: Second) .

    推荐文章