您可以解压缩pony模式匹配中的值吗?

时间:2018-09-09 13:33:13

标签: destructuring ponylang

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 个答案:

答案 0 :(得分:2)

我假设您具有这样的附带定义:

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)形式的元组支持这种模式。