This is an automated archive made by the Lemmit Bot.

The original was posted on /r/programminglanguages by /u/useerup on 2023-10-20 01:43:25.


many languages have a ternary operator for expression if-then-else. Going back to C, it sports the archetypical ternary operator for conditional expression:

condition ? truepart : falsepart

In many languages this is the only ternary operator. So much so, that it has become known as the ternary operator.

For various reasons, I try to design a language with only binary and unary operators. And something about ? : has always bothered me, like e.g. how would you define operator overloading for ternary operators. I’m not claiming it cannot be done, but somehow it feels “off”.

My idea now is to define a binary operator to return an either-or function. For this example, lets adopt the C : operator (ignore what other syntax this may affect):

0 : 42

Such a either-or is a function accepting a boolean argument. If true it evaluates to the left hand value; if false it evaluates to the right hand value.

Now imagine that ? is the “invoke” operator which invokes the function on the right with the argument on the left.

value = condition ? 0 : 42

Obviously the : needs to have higher precedence than ?. Otherwise we would have to write

value = condition ? (0 : 42)

For my language I am not going to use ? and :. Instead I will (probably) use |> and --, respectively:

value = condition |> 0 -- 42

or on separate lines:

value == condition
         |> 0    // then
         -- 42   // else

This allows for some interesting variations, like assigning the either-or expression to a variable before the switching expression:

eitheror = 0 : 42
value = condition |> eitheror

Now, the C ternary operator is also lazy: It only evaluates the true or false part as indicated by the condition. To preserve that part of the semantic, the language needs to be lazy.