F#和类型推断:"int list"不支持"+" [英] F# and type inference: "int list" does not support "+"
问题描述
为什么以下内容会产生错误?
Why does the following generate an error?
let mult a b = a * b
let sum a b = a + b
第二个let产生编译错误:
The second let generates a compile error:
为类型推断变量应用默认类型"int列表"时,类型约束不匹配.类型"int列表"不支持任何名为"+"的运算符,请考虑添加其他类型约束
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
我不明白.为什么假定我正在输入列表?
I don't get it. Why does it assume I'm inputting a list?
完整列表:
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
一旦我在sum函数的末尾添加了0,它就可以正确编译.
Once I added a 0 at the end of the sum function, it compiled correctly.
推荐答案
在声明的末尾添加0有助于编译器推断sum
函数的返回类型:
Adding a 0 to the end of the declaration helped the compiler infer the return type of the sum
function:
let mult a b = a * b
let sum a b = a + b + 0
这篇关于F#和类型推断:"int list"不支持"+"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!