【问题标题】:F# tuple, System.Tuple and collection - Type constraint mismatch?F# 元组、System.Tuple 和集合 - 类型约束不匹配?
【发布时间】:2017-05-09 18:44:53
【问题描述】:

以下代码最后两行编译错误?

open System

let s = new System.Collections.Generic.Stack<Tuple<int, int>>()
s.Push( 1, 2) // The type ''a * 'b' is not compatible with the type 'Tuple<int,int>'
s.Push(Tuple.Create(1, 2))

s.Push(Tuple.Create(1, 2))的错误信息

类型约束不匹配。方式 ''a *'b' 与类型不兼容 '元组' ''a * 'b' 类型与 'Tuple' 类型不兼容 类型元组 = 静态成员 Create : item1:'T1 -> Tuple + 7 重载 全名:System.Tuple

【问题讨论】:

    标签: f#


    【解决方案1】:

    虽然 F# 元组以编译形式用 System.Tuple 表示,但从逻辑语言的角度来看,它们不被视为它的“别名”。

    就 F# 编译器而言,int * intSystem.Tuple&lt;int, int&gt; 不同。

    只需对 Stack 泛型参数使用 F# 元组语法,它就可以工作:

    let s = new System.Collections.Generic.Stack<int * int>()
    s.Push( 1, 2)
    

    【讨论】:

    • 最奇怪的是let t = Tuple.Create(1,2) 得到了int*int 的类型t 而不是Tuple&lt;int, int&gt;
    • 这确实很奇怪。我已将其报告为问题:github.com/Microsoft/visualfsharp/issues/3016
    • 唐关闭了这个问题。不过,我认为 F# 编译器至少应该给出一些解释——这样人们就不会感到困惑了。
    • 欢迎对这个问题发表评论。
    猜你喜欢
    • 2021-10-09
    • 2023-04-09
    • 2016-11-13
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多