2012-02-04 66 views
-4

为什么以下内容会产生错误?F#和类型推断:“int list”不支持“+”

let mult a b = a * b 
let sum a b = a + b 

第二送生成编译错误:

Type constraint mismatch when applying the default type 'int list' for a type inference variable. The type 'int list' does not support any operators named '+' Consider adding further type constraints

我不明白这一点。为什么它假设我正在输入一个列表?

全面上市:

let sampleTimeSeries = 
    dict [ 
    "20110131", 1.5; 
    "20110228", 1.5; 
    "20110331", 1.5; 
    "20110431", 1.5; 
    "20110531", 1.5; 
] 
// Recursive reduce function 
// func : The function to apply 
// terminatingvalue : The terminating value 
// sequence : The list to apply the value on. 
let rec reduce func sequence terminatingValue:int = 
    match sequence with 
    | [] -> terminatingValue 
    | h::t -> func h (reduce func t terminatingValue) 

let mult a b = a * b 
let sum a b = a + b + 0 

有一次,我在和函数的最后增加了一个0,它正确编译。

+6

不是一个错误,我的F#2.0.0.0 - 也许你有一些早期的代码引起错误? – 2012-02-04 04:26:13

+5

这个问题很可能出现在下面的代码*这个片段中,其中使用了sum。 – kkm 2012-02-04 10:22:13

+1

更新后的代码在'fsi'和'fsc'中都很好 - 您确定这是提供错误的代码吗? – 2012-02-04 14:41:03

回答

-1

添加一个0到声明的末尾帮助编译器推断sum函数的返回类型:

let mult a b = a * b 
let sum a b = a + b + 0 
+1

我不认为这是真正的答案 - 这里还有其他一些潜在的问题导致问题。虽然这可行,但不应该要求所有发布的示例运行良好,而不需要额外的'0' – 2012-02-06 22:34:16

相关问题