问题
Why does the following generate an error?
let mult a b = a * b
let sum a b = a + b
The second let generates a compile error:
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?
Full listing:
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
Once I added a 0 at the end of the sum function, it compiled correctly.
回答1:
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
来源:https://stackoverflow.com/questions/9138368/f-and-type-inference-int-list-does-not-support