F#。是否为元组
我刚刚开始学习 F#。
我想知道如何确定函数的参数是否是元组?
let tuple = (1, 2)
let notTuple = 3
let isTuple t = // returns 'true' if t is a tuple, 'false' otherwise
printfn "%b" isTuple tuple // true
printfn "%b" isTuple notTuple // false
I’ve just started learning F#.
I wonder how can I determine whether the argument of a function is a tuple?
let tuple = (1, 2)
let notTuple = 3
let isTuple t = // returns 'true' if t is a tuple, 'false' otherwise
printfn "%b" isTuple tuple // true
printfn "%b" isTuple notTuple // false
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
FSharpType.IsTuple
[MSDN]这样做。FSharpType.IsTuple
[MSDN] does this.从技术上讲,可能有一种方法可以做到这一点,因为 CLR 支持运行时类型检查。但您不应该想要这样做。它违背了 ML 系列的多态性理念——如果您需要这样的检查,则表明您的算法和/或数据结构设计不太适合该编程语言。 (例外情况是,如果您需要与不遵循此理念的现有 .net 库进行交互)。
更具体地说,参数多态性基于这样的概念:每当你有一些你还不知道它是什么类型的东西,这是因为你想要以相同的方式处理所有内容,而不是查看数据内部看看它是什么。不遵循此规则相当于违背编程语言的原则,并且会使您的代码更难以理解,因为类型不会携带有关函数如何处理数据的常用信息。
如果您想创建一些可以传递元组或单个数字的代码,并且让该代码了解差异,您应该定义一个显式的变体类型,以便您可以告诉可能性除了使用模式匹配之外,它们为调用者提供这样的选择的函数类型将是明确的。
There is probably, technically, a way to do this, since CLR supports run-time type checks. But you shouldn't want to do it. It goes against the polymorphism philosophy of the ML familiy -- if you need such a check it indicates that your algorithm and/or datastructure design is not well suited to the programming language. (The exception is if you need to interface with existing .net libraries that don't follow this philosophy).
More specifically, parametric polymorphism is based on the concept that whenever you have something that you don't already know what type it is, it is because you want to handle everything identically and not look inside the data to see what it is. Not following this rule amounts to working against the grain of the programming language, and will make your code harder to understand, because the types will not carry the usual information about how your functions treat data.
If you want to create some code that you can pass either a tuple or a single number, and have that code be aware of the difference, you should define an explicit variant type such that you can tell the possibilities apart using pattern matching, and it will be explicit in the types of the functions that they provide the caller with such a choice.