destructuring - 你能解压小马模式匹配中的值吗?
问题描述
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
但这并不好,特别是如果有多个可能的类要匹配。
解决方案
我假设你有这样的附带定义:
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)
。
推荐阅读
- aggregate - ASP Clingo - 获取原子的确切数量
- javascript - messageParent 适用于桌面 Word 但不适用于 Web Word
- mysql - Mysql - 如何仅计算唯一访问次数
- r - 为什么 geom_rect 在各个方面看起来不同?
- node.js - Express rest api 在邮递员和开发中工作,但在部署时不工作
- php - Laravel 8 [Route: shop.show] [URI: {language}/shop/{shop}] 缺少必需的参数
- javascript - 更新数组反应钩子中数组的状态 onChange
- if-statement - 创建嵌套 if 语句。如果单元格 K2 或 D2 在
- python - 将多个蜘蛛的输出捕获到单个输出文件/变量中的正确“抓取”方式是什么?
- powershell - 枚举给定 ProgID 的 COM 对象公开的方法和属性