September 2002
Functions and Infix Operators
Overview
The use of infix operators provides humans with visual cues about the intended meaning of source code. The visual distinctiveness it provides allows faster recognition of the operation in question, shorter code, and fewer keystrokes.
Clarity and Efficiency
The best example of visual distinctiveness provided by an infix operator can be found in object oriented languages; in the use of the dot.
Functional:
doSomething(A, B)
Lisp
(doSomething A B)
Infix
A.doSomething(B)
I like to describe the conversion between functional notation and infix operators as "pulling out" parameters. As we can see, we have removed a function parameter (A) and replaced it with an operand (".").
The most common use of infix operators in math, and are a good example of shorter code. Here, the use of precedence is necessary to provide an implied order of operations, and effectively reduce code size.
Functional:
add(mult(a, b), mult(c,d))
Lisp
(+ (* a b) (* c d))
Infix
a * b + c * d
String Concatenation
The use of "+" to concatenate strings confuses that with numerical addition. Therefore, with an almost infinite supply of possible operators, we should choose another for clarity. In the following examples the functions are assumed to be able to accept a number and convert it to string for concatenation.
Functional
append(A, 3+9, B)
Object Oriented
A.append(3+9).append(B)
"+" for string concatenation
A + (3+9) + B
"|" for string concatenation
A | 3+9 | B
Although, I prefer an "append" operator over the pipe symbol because it is easier to remember.
KMAL Infix Operators
Due to the demand that all parameters are keyword parameters in KMAL, the advantages of pulling out parameters is even greater.
Extreme Example
We are limited in the number of parameters we can pull out in a lexical language: one to the right and one to the left. Yet, we do not need to limit our operators to be literals, but rather any programming construct, most notably functions. We use a standard search and replace function for our example. The right column is KMAL code.
Functional
replace(A, B, C) replace(value=A, find=B, replace=C)
Object Oriented
A.replace(B, C) A.replace(find=B, replace=C)
Infix
A replace(B) C A replace(find=B) C
Summary
Puling out parameters, and using infix operators is a good thing for improving code readability, and reducing code size.