F# and type inference: “int list” does not support “+” [closed]

帅比萌擦擦* 提交于 2019-12-27 06:15:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!