Reputation: 37045
In F#, can two functions with different arity and return types share a name?
For example, with 2 arguments, f
returns an int
:
let f (x:int) (y:int) : int = x + y
But with 3 arguments, f
returns a bool
:
let f (x:bool) (y:bool) (z:bool) : bool = x & y & z
It seems like the return type should be inferable by the number of arguments given, but I get the compilation error:
Duplicate definition of value 'f'
Is this a limitation of F#?
Upvotes: 3
Views: 1040
Reputation: 26174
Let's analyse both features:
This is not trivial in F# as in other functional languages, but it's possible and at some point they make sense. Typical examples are the math operators, they return different types based on the input parameter types, so in the end what you have is a single generic function. This in not the same idea as method overloading where you have many methods which share the name.
This is even less trivial, also in other functional languages with automatic currying, because it will conflict with that feature. Still there are some (few) cases where they might make sense, here's an example coming from Haskell.
This makes practically no sense, the idea behind overloaded functions is to have a relationship between the types of the input (and maybe also the output) arguments of the different overloads which would feel as a single generic function. So in this case it resemble more .NET method overloading which by the way is a feature supported in F#.
Finally, using some hacks you can encode your example in F#:
let f (x:int) (y:int) : int = x + y
let g (x:bool) (y:bool) (z:bool) : bool = x & y & z
type T = T with
static member ($) (T, x) = fun y -> f x y
static member ($) (T, x) = fun y z -> g x y z
let inline myFunc x y = (T $ x) y
let result1 = myFunc 3 5
let result2 = myFunc true false true
But again, I don't think it's a good idea.
Upvotes: 5