Custom infix operators

I started thinking of this after mucking around with Python’s os module a lot more recently.

Some languages, notably Haskell, allow you to define your own infix operators. For example, using a mix of Python and Haskell pseudocode, (+/+) path1 path 2 = os.path.join(path1, path2) would make the os module a lot more concise, and in my opinion, readable.

There is a trade-off in readability when you use infix operators. For a lot of things, infix operators are like one letter variable names: they’re hard to understand. In other contexts, anything but than a one letter variable name would just be unnecessarily long. Compare the following examples:

plus(var, plus(first_var, second_var))
x + y + z

For the most commonly used operations, it makes sense to define infix operators because you can think of that operation in a sort of abstract way, where you no longer really need to know the name of it because what it does is well internalized at that point. On the other hand, look at any Haskell library for a great example of how abusing them creates write-only code.

It seems Python’s maintainers agree with me to some degree.

Another idea I like (that Haskell also does) is turning prefix operators into infix by surrounding them in some symbol (Haskell uses backticks).

x `plus` y
x `mod` y
path1 `join` path2

This is both readable, searchable, and retains the benefits of infix operators.

Infix operators make parsing a little more annoying, but you can always follow Scala’s approach for parsing and Fortress’s approach for operator precedence. I’ll let you read about what those are because it’s late and I’m ~lazy~ tired.

Related Posts

Just because 2 things are dual, doesn't mean they're just opposites

Boolean Algebra, Arithmetic POV

discontinuous linear functions

Continuous vs Bounded

Minimal Surfaces

November 2, 2023

NTK reparametrization

Kate from Vancouver, please email me

ChatGPT Session: Emotions, Etymology, Hyperfiniteness

Some ChatGPT Sessions