How useful are infix operators in a programming language? Are they worth the extra complexity they provide? Can you provide any examples where infix operators are better suited to the problem that can't be handled by just overloading the normal operators?
I think infix operators stem from mathematics.
2 + 3 * 4
is more readable to most people, than
(+ 2 (* 3 4))
because most people are familiar with mathematics.
Interesting enough in Haskell you can hop between infix and prefix. This is using the same funtion "(+)":
(+) 1 2 1 + 2
and this is using the same function "elem":
elem 42 [1,2,42] 42 `elem` [1,2,42]
Computer languages are designed for humans not machines. And humans are more used to infix operators than pre or postfixes.
The only real reason for infix operators is that humans generally find them easier to read. This is largely due to two facts:
- We learn infix operators in the form of mathematics from an early age and hence are familiar with them:
2 * 2 = 4etc.
- An infix operator has the advantage of "visually" separating two arguments. e.g.
(some complex expression) + (some other complex expression)
From a logical/machine perspective, infix operators don't really add any value and in some cases are a nuisance:
- You can always convert from infix to an equivalent function call with two arguments - so infix operators are never more than "syntactic sugar"
- Infix can be inconvenient when you want to use more than two parameters.
(* 1 2 3 4 5)in Lisp for example is arguably a much cleaner syntax for multiplying a set of numbers.
- From a parsing perspective, it's often useful to read the operator first so that you know how to interpret the remainder of the expression. With infix operators this can be much more complex (e.g. you have to maintain a stack or something similar to figure out which operator applies to which arguments)
- In stack-based/concatenative languages such as Forth, you want the operator to be pushed on the stack last, so that it already has its arguments in the right position. Again, burying the operator in the middle of a sequence of tokens only complicates matters.
- Infix operators can get very confusing indeed when they are overloaded - what does "+" mean when applied to two HashMaps for example? Here, the intuitive human understanding of the infix operator works against you because it's easy to assume a meaning that wasn't actually intended.....