Function Arguments with Multiple Types

Bob4 none at gmail.com
Fri Sep 6 20:02:35 UTC 2019


Hi,

I'm coming from a background in Python, without a lot of 
experience in statically typed languages, and I'm struggling to 
see how to make a certain function in D.

This is what I have in Python:

```
from typing import Union

Number = Union[int, float]

def clamp(value: Number, mini: Number, maxi: Number) -> Number:
     if value >= maxi:
         return maxi
     if value <= mini:
         return mini
     return value
```

In Python, I could supply this function with any type really; it 
doesn't type check, and essentially only runs 
`value.__ge__(maxi)` and `value.__le__(mini)`. How can I simulate 
this in D? There are already implementations of `clamp` out 
there, but that isn't the point.

I hear that there is a "variant" type, that allows one to pass 
any type; but I either want to restrict it to certain types, or 
only to types that possess some kind of `__ge__` or `__le__` 
method. The only way I found on how to do the former was 
overloading, like:

```
bool test(int a) {...}
bool test(float a) {...}
```

Unfortunately this doesn't seem to work well with the return 
type, and I feel like it's wrong to rewrite identical functions 
over and over.


More information about the Digitalmars-d-learn mailing list