TK.*_*TK. 2 f# inline type-resolution
我刚刚开始使用F#,但我有一些类似于以下内容的代码:
let square x = x*x
let result = square 5.1
let result' = square 12
Run Code Online (Sandbox Code Playgroud)
不幸的是,这会导致以下错误: This expression was expected to have type float but here has type int
这个问题是否有惯用的F#解决方案,还是我的想法被我的C#体验所污染?
就这样写:
let inline square x = x * x
Run Code Online (Sandbox Code Playgroud)
否则,在您第一次使用该square函数后,它的类型被推断为float -> float.因此,如果F#没有自动转换int为float,则会收到错误.
所以,如果你不想使用inline,最简单的解决方案就是写
let result' = square (float 12)
Run Code Online (Sandbox Code Playgroud)
它简单易读.
有关更高级的解决方案,请看一下:F#是否具有通用算术支持?
但这些解决方案(imho)难以理解.