Is there a programming language (may be a concept or research paper), which allows a polymorphism over function/method arguments values? Kind of:
function factorial(int value > 0){ /* code here */}
function factorial(int value == 0){ /* code here */}
function factorial(int value < 0){ /* code here */}
And, what is the official name, if any, for this kind of polymorphism?
I guess what you're looking for is pattern matching and/or guards. Erlang for instance allows this:
foo(X) when X > 0 -> bar(X);
foo(X) when X == 0 -> baz(X);
foo(X) -> X.
foo("bar", X) -> bar(X);
foo(42, X) -> baz(X);
foo(_, X) -> X.
The former demonstrates the use of guards, the latter is a simple pattern match, where the first argument is either "bar"
, 42
or anything else. Both techniques can be found in many functional languages.
Just in case you're not familiar with the syntax, that's equivalent to (as much as it can be compared):
function foo("bar", x) {
return bar(x);
}
function foo(42, x) {
return baz(x);
}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With