2016-02-29 44 views
1

匹配不同類型的我試圖用「內聯」定義將融入不同的輸入參數類型的函數:F#:仍然不能爲通用功能

> let x=2.0 
- let inline f x=x+1 
- f x;; 

    f x;; 
    --^ 

stdin(6,3): error FS0001: This expression was expected to have type 
    int 
but here has type 
    float 

我希望申請後,「內聯「在f上,我得到了一個泛型函數調用」f「。但似乎失敗了。 如何糾正它?

回答

5

最好的辦法是使用genericOne像這樣:

let inline f x = x + LanguagePrimitives.GenericOne 

這是因爲當你使用1,編譯器infered,函數參數必須是int,你只能添加ints到其他ints

那麼你就可以

> f 1;; 
val it : int = 2 
> f 1.0;; 
val it : float = 2.0 
叫它
1

這是因爲你在你的函數中加入了1。因爲那x必須是int。如果您提供的+雙方作爲參數

inline將工作:

> let inline f x y = x + y;; 

val inline f : 
    x: ^a -> y: ^b -> ^c 
    when (^a or ^b) : (static member (+) : ^a * ^b -> ^c) 

正如你可以看到,它的類型被解析爲任何類型的+。你可以用它來添加兩個int小號or two float`s在一起:

> f 1 2;; 
val it : int = 3 
> f 1. 2.;; 
val it : float = 3.0 

但是,您不能使用它來添加intfloat

> f 1. 2;; 

    f 1. 2;; 
    -----^ 

stdin(9,6): error FS0001: The type 'int' does not match the type 'float'