为什么不允许在“使用"模式中使用模式?绑定? [英] Why aren't patterns allowed in "use" bindings?

查看:86
本文介绍了为什么不允许在“使用"模式中使用模式?绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据规范use绑定需要标识符(不同于let)而不是模式.为什么是这样?这是一个不起作用的方案的示例.

According to the spec, a use binding requires an identifier (unlike let) instead of a pattern. Why is this? Here's an example of a scenario that doesn't work.

type Disposable = Resource of IDisposable

let f disposable =
  use (Resource d) = disposable //ERROR: 'use' bindings must be of the form 'use <var> = <expr>'
  ()

推荐答案

我认为可能的答案是很多模式都没有意义.例如,您希望编译器如何处理以下代码?

I think the likely answer is that lots of patterns don't make sense. For instance, how would you expect the compiler to handle the following code?

type DisposablePair = DisposablePair of IDisposable * IDisposable

let f disposablePair =
    use (DisposablePair(x,y)) = disposablePair
    ()

您的奇怪错误消息可能是由于以下事实:即使您使用的是let绑定,也需要绑定(Resource d)而不是Resource(d)(编译器认为您正在声明一个新函数).

Your weird error message is probably due to the fact that even if you were using a let binding, you'd need to bind (Resource d) rather than Resource(d) (the compiler thinks you're declaring a new function).

对于它的价值,我确实发现有时无法使用下划线模式是一件烦人的事情(尤其是在处理仅用于划分作用域(例如,System.Transactions.TransactionScope)而存在的IDisposable实例时).通用化use绑定以处理下划线和其他几种情况的一种方法是要求use绑定的右侧为IDisposable,但允许左侧的任何模式,以便:

For what it's worth, I do find the inability to use an underscore pattern to be an annoyance at times (particularly when dealing with IDisposable instances that exist only to demarcate scopes, like System.Transactions.TransactionScope). One way to generalize use bindings to handle underscores and a few other situations would be to require the right hand side of a use binding to be an IDisposable but to allow any pattern on the left hand side, so that:

use p = v in e 

在语法上会翻译成类似的东西

would syntactically translate to something like

let ((p:System.IDisposable) as d) = v in try e finally d.Dispose()

这篇关于为什么不允许在“使用"模式中使用模式?绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆