Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism over argument values (not types)?

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?

like image 575
ts. Avatar asked Dec 21 '22 02:12

ts.


1 Answers

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);
}
...
like image 118
deceze Avatar answered Jan 02 '23 10:01

deceze