How can I extend a primitive type

Perhaps you’re right, I guess I like functions where the types are helping to document the function. This, again comes from Python where we type hint and rarely use multiple dispatch. I should re-think my Julia style.

This is something I’ve definitely learnt today.


Just to round off this discussion, what is the Julia equivalent of this python?

>>> class Foo(float):
...     def __init__(self, v) -> None:
...         self.value = v
>>> Foo(2)*2
>>> type(Foo(2))
<class '__main__.Foo'>

Seeing that you’re trying to calculate future salaries, this is something that I implemented a while ago. My solution was just to use a couple of functions. I don’t have the exact code I used but it was something like this

isperc(x) = 0 < x < 1
new_salary(N, x) = isperc(x) ? N*(1+x) : N + x

Here, the raise amount could be a decimal (percent/100) percentage or the total amount (like $2000). This makes the assumption that all total dollar values would be more than $1 though.

1 Like

Interesting so you took a third approach. I think all this comes under the umbrella of coding style, perhaps I’m over-exuberant with multiple dispatch.

Yeah, I’m a “path of least resistance” coder and that solution seemed easiest at the time.

1 Like

In Julia you cannot make subtypes of concrete types — all concrete types are “final”. (This turns out to be crucial for performance!)

You can make a subtype of an abstract type like Real or Number, but then it is a lot more work — the generic Real type doesn’t have definitions for basic operations like * (how could it?). For a relatively simple example defining a new number type, see e.g. Quaternions.jl.


If you are processing data, rather than relying on multiple dispatch later on, just make sure your data is conforming before doing any calculations. For the example you gave earlier, rather than having functions that do x * (1 + change) or x * change, I would make sure that all of my “change” data points (eg. in a DataFrame column) were in gross percent (90% = 1.9). Then I know x * change is going to be fine.

1 Like

Okay, so it seems like this isn’t something worth doing for my purposes.

Thank you, this clearly demonstrates the extra work required.

I don’t know if it’s a coincidence, but this just showed up: GitHub - Mikumikunisiteageru/Logistics.jl

1 Like

Note that, by definition, one percent is one part per hundred (one per centum).

1 Like

Thank you for pointing this out, that looks like a handy package!

The timing is also a fun coincidence.