Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# function overloading with same parameter number

Tags:

f#

I have a simple F# function cost receiving a single parameter amount which is used for some calculations. It is a float so I need to pass in something like cost 33.0 which in math is the same as cost 33. The compiler complaints about it, and I understand why, but I would like being able to call it like that, I tried to create another function named the same and used type annotation for both of them and I also get compiler warnings. Is there a way to do this like C# does?

like image 815
Luiso Avatar asked May 06 '26 01:05

Luiso


1 Answers

There are two mechanisms in F# to achieve this, and both do not rely on implicit casts "like C#":

(A) Method overloading

 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

(B) Using inlining

let inline cost amount =
    amount + amount

cost 10   // compiles OK
cost 10.  // compiles OK
like image 191
Gene Belitski Avatar answered May 09 '26 09:05

Gene Belitski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!