F#函数重载参数号相同

Lui*_*iso 2 f#

我有一个简单的F#函数cost接收一个参数amount,用于一些计算.这是一个float所以我需要传递一些像cost 33.0数学一样的东西cost 33.编译器抱怨它,我理解为什么,但我希望能够这样调用它,我试图创建另一个名为相同的函数,并为它们使用类型注释,我也得到编译器警告.有没有办法像C#那样做?

Gen*_*ski 7

F#中有两种机制来实现这一点,并且都不依赖于隐式转换"像C#":

(A)方法重载

 type Sample =
     static member cost (amount: float) =
         amount |> calculations
     static member cost (amount: int) =
         (amount |> float) |> calculations

 Sample.cost 10   // compiles OK
 Sample.cost 10.  // compiles OK
Run Code Online (Sandbox Code Playgroud)

(B)使用内联

let inline cost amount =
    amount + amount

cost 10   // compiles OK
cost 10.  // compiles OK
Run Code Online (Sandbox Code Playgroud)