F#的底线:为什么不仅仅创建一个变量名? [英] F#'s underscore: why not just create a variable name?

查看:51
本文介绍了F#的底线:为什么不仅仅创建一个变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天阅读有关F#的内容,但我不清楚一件事:

Reading about F# today and I'm not clear on one thing:

来自: http://msdn.microsoft.com/en-us/library/dd233200.aspx

您只需要一个元组元素,通配符(下划线)可用于避免为不需要的变量创建新名称

让(a,_)=(1,2)

let (a, _) = (1, 2)

我想不起曾经有过这种情况.为什么要避免创建变量名?

I can't think of a time that I've been in this situation. Why would you avoid creating a variable name?

推荐答案

有趣的问题.这里涉及很多折衷.

Interesting question. There are many trade-offs involved here.

您的比较已经与Ruby编程语言进行了比较,因此也许您应该考虑的第一个权衡是静态类型.如果使用模式x, _, _,则F#知道您是在指正好三个元素中的三个元素中的第一个元素,并且将在编译时强制执行此约束.露比不能F#还检查模式的详尽性和冗余性.再说一次,Ruby不能.

Your comparisons have been with the Ruby programming language so perhaps the first trade-off you should consider is static typing. If you use the pattern x, _, _ then F# knows you are referring to the first element of a triple of exactly three elements and will enforce this constraint at compile time. Ruby cannot. F# also checks patterns for exhaustiveness and redundancy. Again, Ruby cannot.

您的比较也只使用了扁平模式.考虑模式_, (x, _)x, None | _, Some x[] | [_],依此类推.这些不是那么容易翻译.

Your comparisons have also used only flat patterns. Consider the patterns _, (x, _) or x, None | _, Some x or [] | [_] and so on. These are not so easily translated.

最后,我要提到Standard ML是一种与F#相关的编程语言,它确实提供了称为#1等的运算符,以提取具有任意数量的元素的元组的第一个元素(请参见此处),因此这个想法在几十年前就已实施并被放弃.我相信这是因为SML的#n表示法在类型系统的约束内最终导致了无法理解的错误消息.例如,使用#n的函数无法清楚说明元组的Arity是什么,但是不能通过元组Arity泛型使用函数,因此这必定会导致错误消息,提示您必须提供更多的类型信息,但发现许多用户那令人困惑.使用CAML/OCaml/F#方法不会出现这种混淆.

Finally, I'd mention that Standard ML is a programming language related to F# and it does provide operators called #1 etc. to extract the first element of a tuple with an arbitrary number of elements (see here) so this idea was implemented and discarded decades ago. I believe this is because SML's #n notation culminates in incomprehensible error messages within the constraints of the type system. For example, a function that uses #n is not making it clear what the arity of the tuple is but functions cannot be generic over tuple arity so this must result in an error message saying that you must give more type information but many users found that confusing. With the CAML/OCaml/F# approach there is no such confusion.

这篇关于F#的底线:为什么不仅仅创建一个变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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