[英]f# idiomatic type resolution solution for resolving to the wrong type
我剛剛開始使用F#,但我有一些類似於以下內容的代碼:
let square x = x*x
let result = square 5.1
let result' = square 12
不幸的是,這會導致以下錯誤: This expression was expected to have type float but here has type int
是否有一個慣用的F#解決這個問題的方法,還是我的想法被我的C#體驗所污染?
就這樣寫:
let inline square x = x * x
否則,在第一次使用該square
函數后,它的類型被推斷為float -> float
。 因此,假設F#沒有從int
到float
自動轉換,則會收到錯誤。
因此,如果您不想使用inline
,最簡單的解決方案是編寫
let result' = square (float 12)
它簡單易讀。
有關更高級的解決方案,請看一下: F#是否具有通用算術支持?
但這些解決方案(imho)難以理解。
let inline square x = x * x
let result = square 5.1
let result' = square 12
printfn "%f" result
printfn "%d" result'
Tomas Petricek撰寫了一篇關於這個主題的文章: http ://tomasp.net/blog/fsharp-generic-numeric.aspx/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.