首页 > 解决方案 > 你能解压小马模式匹配中的值吗?

问题描述

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

但这并不好,特别是如果有多个可能的类要匹配。

标签: destructuringponylang

解决方案


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

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)


推荐阅读