57

Is there a math equivalent of the ternary conditional operator as used in programming?

a = b + (c > 0 ? 1 : 2)

The above means that if $c$ is greater than $0$ then $a = b + 1$, otherwise $a = b + 2$.

Wharf Rat
  • 264
  • 2
  • 11
dataphile
  • 752
  • 1
  • 5
  • 14
  • It probably depends on the form of the conditions and the results, but the example you gave can be expressed with the [unit step](https://en.wikipedia.org/wiki/Heaviside_step_function) $u(x)$ (with an appropriate definition at $x=1$): $a = u(b+c) + 1$ – Alex Mar 05 '19 at 05:28
  • 5
    @Alex $a = b + 2 - u(c)$ – eyeballfrog Mar 05 '19 at 05:45
  • 20
    A better question here is: what is *good* notation in this case. There are many ways of writing this, many ways which one would almost never use (like the accepted answer). – Winther Mar 05 '19 at 09:04
  • 5
    In C-derived languages at least, you have made a grievous error! Your expression parses as `a = (b + c) > 0 ? 1 : 2`. I always use parentheses in these cases, even when they are not strictly necessary. – TonyK Mar 05 '19 at 11:38
  • 3
    Just to clarify, by “ternary operator” you really mean “*conditional* operator”? Or are interested in *any* kind of ternary operator, regardless of semantics? – Konrad Rudolph Mar 05 '19 at 15:21
  • 1
    What @KonradRudolph said; you are showing the *conditional* operator, which is a ternary (takes three arguments; compare unary and binary) operator. I don't think the C language has any other ternary operator, and some form of the conditional operator is found in many languages because it's very convenient to have, but there's no rule that says a language couldn't include other ternary operators alongside (or without having) a conditional operator. – user Mar 05 '19 at 15:44
  • Thanks for highlighting this. I’ve now clarified the title. – dataphile Mar 05 '19 at 16:55
  • By "ternary operator" do you mean "(c > 0 ? 1 : 2)", rather than the whole RHS? That's not really an operator in the mathematical sense, since its arguments aren't of the same type (the first is a boolean, the other two are int). – Acccumulation Mar 05 '19 at 23:26
  • 1
    From Wikipedia: “Although many ternary operators are possible, the conditional operator is so common, and other ternary operators so rare, that the conditional operator is commonly referred to as the ternary operator.” It is called “the ternary operator” in computer science, hence the “computer-science” tag. I was looking for the math equivalent as is evident from the detail. It doesn’t have to be “ternary” or an “operator” in mathematics. – dataphile Mar 06 '19 at 05:53
  • I think the question title would be more accurate if, rather than asking for a "math expression equivalent", it asked for a widely-recognized notation for this in a mathematical context. – R.. GitHub STOP HELPING ICE Mar 08 '19 at 14:56
  • It's unclear from the question if you really want a math expression for the general ternary operator `x ? y : z` or just a way to convert the particular expression `b + (c > 0 ? 1 : 2)` into a more typically mathematical notation. The answers to those two questions are related but different. – David K Mar 08 '19 at 15:01
  • I'm a little late to this question, but there doesn't otherwise seem to be any mention of Hoare's "ternary conditional" notation: `y ⊲ x ⊳ z`, which is equivalent to `if x then y else z`. (From his book *Communicating Sequential Processes* [1985]) – Steve Jan 26 '21 at 01:12

14 Answers14

80

From physics, I'm used to seeing the Kronecker delta,$$ {\delta}_{ij} \equiv \left\{ \begin{array}{lll} 1 &\text{if} & i=j \\ 0 &\text{else} \end{array} \right. _{,} $$and I think people who work with it find the slightly generalized notation$$ {\delta}_{\left[\text{condition}\right]} \equiv \left\{ \begin{array}{lll} 1 &\text{if} & \left[\text{condition}\right] \\ 0 &\text{else} \end{array} \right. $$to be pretty natural to them.

So, I tend to use $\delta_{\left[\text{condition}\right]}$ for a lot of things. Just seems so simple and well-understood.

Transforms:

  1. Basic Kronecker delta:
    To write the basic Kronecker delta in terms of the generalized Kronecker delta, it's just$$ \delta_{ij} \Rightarrow \delta_{i=j} \,.$$It's almost the same notation, and I think most folks can figure it out pretty easily without needing it explained.

  2. Conditional operator:
    The "conditional operator" or "ternary operator" for the simple case of ?1:0:$$ \begin{array}{ccccc} \boxed{ \begin{array}{l} \texttt{if}~\left(\texttt{condition}\right) \\ \{ \\ ~~~~\texttt{return 1;} \\ \} \\ \texttt{else} \\ \{ \\ ~~~~\texttt{return 0;} \\ \} \end{array} ~} & \Rightarrow & \boxed{~ \texttt{condition ? 1 : 0} ~} & \Rightarrow & \delta_{\left[\text{condition}\right]} \end{array} _{.} $$Then if you want a non-zero value for the false-case, you'd just add another Kronecker delta, $\delta_{\operatorname{NOT}\left(\left[\text{condition}\right]\right)} ,$ e.g. $\delta_{i \neq j} .$

  3. Indicator function:
    @SiongThyeGoh's answer recommended using indicator function notation. I'd rewrite their example like$$ \begin{array}{ccccc} \underbrace{a=b+1+\mathbb{1}_{(-\infty, 0]}(c)} _{\text{their example}} & \Rightarrow & \underbrace{a=b+1+ \delta_{c \in \left(-\infty, 0\right]}} _{\text{direct translation}} & \Rightarrow & \underbrace{a=b+1+ \delta_{c \, {\small{\leq}} \, 0}} _{\text{cleaner form}} \end{array} \,. $$

  4. Iverson bracket:
    Iverson bracket notation, as suggested in @FredH's answer, is very similar to the generalized Kronekcer delta. For example:$$ \delta_{i=j} ~~ \Rightarrow ~~ \left[i = j \right] \,.$$Dropping the $`` \delta "$ reduces backwards-compatibility withe the basic Kroncker delta, plus it weakens the signal about what the notation means, so it's probably not as good in general contexts right now. However, Iverson bracket notation should be easier to read and write, so when reinforcing the meaning of the notation isn't a big issue, it could be preferable.


Note: "Conditional operator" rather than "ternary operator".

The conditional operator, condition ? trueValue : falseValue, has 3 arguments, making it an example of a ternary operator. By contrast, most other operators in programming tend to be unary operators (which have 1 argument) or binary operators (which have 2 arguments).

Since the conditional operator is fairly unique in being a ternary operator, it's often been called "the ternary operator", leading many to believe that that's its name. However, "conditional operator" is more specific and should generally be preferred.

Nat
  • 1,434
  • 1
  • 10
  • 15
  • 1
    wow, this is beautiful. I need it for an infinite series (with some elements excluded i.e. multiplied by zero and others included, multiplied by 1) so this cleaner form is exactly what I need. – dataphile Mar 05 '19 at 15:05
  • @dataphile Yeah, the Kronecker delta's great for specifying elements like that; it comes in handy if you're using [Sigma](https://en.wikipedia.org/wiki/Sigma_notation#Capital-sigma_notation)/[Pi](https://en.wikipedia.org/wiki/Pi_notation#Capital_Pi_notation)/[Einstein](https://en.wikipedia.org/wiki/Einstein_notation) notations. Worth noting that it's basically the integrated Dirac delta; if you're working in a continuous domain, then the Dirac delta tends to be preferred, though it's largely the same thing. – Nat Mar 05 '19 at 15:11
  • 3
    The Kronecker delta isn’t a ternary operator, it’s a plain old binary operator, since it has two operands. – Konrad Rudolph Mar 05 '19 at 15:22
  • @KonradRudolph Yeah, gotta add a $\delta_{\operatorname{NOT}\left(\left[\text{condition}\right]\right)}$-term to get that `false`-case behavior in there when it's non-zero. – Nat Mar 05 '19 at 15:24
  • 3
    The $1$-if-condition-else-$0$ generalisation of the Kronecker delta is called the [Iverson bracket](https://en.wikipedia.org/wiki/Iverson_bracket). We can generalise to any two input values we like with a suitable function, of domain $\{0,\,1\}$, wraping the Iverson bracket. – J.G. Mar 05 '19 at 17:17
  • @KonradRudolph The third operand is the function of domain {0, 1} – Caleth Mar 05 '19 at 23:55
  • @KonradRudolph: important point, but ¿binary? – the above generalised Kronecker delta is unary, since it takes only one argument, namely the condition. – PJTraill Mar 06 '19 at 20:16
  • This generalised Kronecker delta is a long way from providing a compact and intuitive way of writing `(c?x:y)`. It is fine if you want $1$ or $0$ as results, awkward if you want other members of a ring, when we get $ δ _c (x) + δ _{\not c} (y) $ – not a success, in my opinion – and fails altogether if $x$ and $y$ are not susceptible of multiplication and addition. – PJTraill Mar 06 '19 at 20:20
  • @PJTraill Mostly out of curiosity, is there a logic to which appending the appropriate multiplication/addition would be problematic? I mean, I know that in a general logic, we can easily append suitably minimal notions of multiplication/addition to make it work, though I can appreciate how a sparse logic with little typing might conceivably frustrate a mathematician not used to dealing with arbitrarily typed objects. Would you happen to have an example of such a logic? In other words, do you know of a logic which couldn't admit the generalized Kronecker delta without obfuscation? – Nat Mar 06 '19 at 21:20
  • @PJTraill For example, we once didn't have a logic of multiplying temperatures, such that temperature scales that didn't zero at absolute zero, e.g. $\sideset{^\circ}{}{\mathrm{C}}$ and $\sideset{^\circ}{}{\mathrm{F}}$, weren't problematic, even when we did multiply temperatures in localized contexts, e.g. in a virial-expansion correlation. But then once we did have a notion of absolute-zero, there was another notion of "_multiplication_" applicable to temperature; which didn't invalidate the prior one, but seems to invite confusion to those used to sparse logic. – Nat Mar 06 '19 at 21:25
  • @PJTraill Anyway, my question's then, is there an analogous logic in which sparse-typing would be inadequate to capture the generalized Kronecker delta? – Nat Mar 06 '19 at 21:27
  • 6
    Tangentially, folks really need to get over the "_ternary operator_" thing. It's a common name, if a misnomer, in programming; it's a strawman to misattribute the general definition to the question statement when it's clearly not what they meant. Further, arity's arbitrary anyway; we may as well say that the addition operator, $`` + " ,$ is actually unary because it doesn't act on two addends but rather the tuple of them. Like in counting degrees of freedom or assigning entropy, just pick some sensible convention and understand it to be subjective. – Nat Mar 06 '19 at 21:32
  • I agree that the arity thing is a sidetrack, not what the question is about. In a language like C it _is_ “the ternary operator” because there it is unique, in maths it is more likely to confuse. Your other question (¿add + & ×?) seems trickier. – PJTraill Mar 06 '19 at 22:21
  • Given a formal system without 0, 1, + & ×, you could extend it by adding them and defining the operations as needed. Verifying that things are well-defined seems trickier; you want a result in the original codomain, so should only allow exactly one non-zero summand. If some of the four symbols were in use with incompatible meanings, it would be doable but messy. It all seems a long, clumsy way round compared with just using a selection operator. Normally of course, mathematicians define piece-wise functions on multiple lines and are often conservative about established notation. – PJTraill Mar 06 '19 at 22:51
  • On the conditional vs. ternary debate... yes people also prefer "hacking" to "cracking" as well. But common usage dictates what language means, minority preference (even if educated and well-informed) doesn't. For evidence of this, note that dictionaries are generally descriptive rather than prescriptive. – Bradley Thomas Mar 07 '19 at 13:09
  • 2
    Finally someone who does't call ?: "the ternary operator". Conditional operator doesn't describe it properly though. It's not an operation that's coditional, but one that selects a value based on a condition. For that reason, I always call it the "selection operator", as that's what it does: based on the condition, select either option A or option B. – Clearer Mar 08 '19 at 13:32
  • @BradThomas That's majoritarianism. It might have some value as a principle to use in designing elections, but mathematical notation's another matter. In maths, a notion doesn't become true as a result of people believing it. – Rosie F Mar 09 '19 at 11:42
  • Could we use otherwise instead of `else`? – alper Feb 11 '22 at 12:58
  • @alper: Both wordings would seem viable; I tend to go with "_else_" because it's shorter. What might be a motivation for using "_otherwise_" instead? – Nat Feb 12 '22 at 04:53
  • @Nat Here (https://tex.stackexchange.com/q/9065/127048) `otherwise`is used. Also examples in the https://www.amazon.com/Mathematical-Notation-Guide-Engineers-Scientists/dp/1466230525 `otherwise` is used. I am not sure which one is prefered. – alper Feb 12 '22 at 13:14
  • @alper: That's a good point; it might be good to prefer "_otherwise_" in general. In the above-answer, I may've used "_else_" to help align the notation with [conditional blocks (`if(){}else{}`)](https://en.wikipedia.org/wiki/Conditional_(computer_programming)#If%E2%80%93then(%E2%80%93else)), to help make the conversion between the two notations more apparent. – Nat Feb 12 '22 at 14:26
65

The expression b + (c > 0 ? 1 : 2) is not a ternary operator; it is a function of two variables. There is one operation that results in $a$. You can certainly define a function $$f(b,c)=\begin {cases} b+1&c \gt 0\\ b+2 & c \le 0 \end {cases}$$

You can also define functions with any number of inputs you want, so you can define $f(a,b,c)=a(b+c^2)$, for example. This is a ternary function.

J. W. Tanner
  • 1
  • 3
  • 35
  • 77
Ross Millikan
  • 362,355
  • 27
  • 241
  • 432
  • 17
    *Ternary operator* in programming means a conditional statement of form "if A then x else y" and uually is written just as presented in the OP, i.e. A ? x : y. It would also literally be termary if the OP wouldn't have inserted the particular values of 1 and 2. – Džuris Mar 05 '19 at 09:40
  • 21
    @Džuris *Ternary* means "of arity 3", like *binary* means "of arity 2" and *unary* "of arity 1". The specific operator is the *conditional ternary operator*. – frabala Mar 05 '19 at 10:08
  • 4
    Yes, that's what the word means. But the term *ternary operator* in programming is exactly THE conditional ternary operator. (https://en.wikipedia.org/wiki/%3F:) – Džuris Mar 05 '19 at 10:10
  • 4
    The general form "condition ? value1 : value2" is a function of *three* variables, not two, because the condition itself is a parameter of the ternary operator. – Zoltan Mar 05 '19 at 10:53
  • 23
    Once again, clarity beats compactness when it comes to mathematics. – Asaf Karagila Mar 05 '19 at 12:25
  • 11
    _Well-chosen_ compact notations can contribute to clarity rather than detract from it, though. – hmakholm left over Monica Mar 05 '19 at 12:34
  • @HenningMakholm Yes, but still the compactness is secondary: given two equally clear notations, the more compact is better, but clarity considerations should still come first in my opinion. – Noah Schweber Mar 05 '19 at 15:07
  • 9
    @Džuris No it isn’t. The link you cite says, in its very first sentence, that “`?:` is *a* ternary operator” (not “*the* ternary operator”; emphasis mine). *Some* people refer to it as “*the* ternary operator” but this is strictly incorrect (and merits a correction e.g. on Stack Overflow). – Konrad Rudolph Mar 05 '19 at 15:25
  • 7
    I want to upvote this because this is the easiest (imo) way to write this in a mathematical context, but I can't because of all the surrounding confusion over CS-specific terminology. (And yes, "the ternary operator" is perfectly correct in a CS context, just like a tomato is a fruit, if the context is biology.) – user3067860 Mar 05 '19 at 15:48
  • 5
    It is unfortunate that the word _TERNAry_, which will be unfamiliar to many who meet it for the first time in programming, lends itself so readily to an assumption that it is somehow related to choosing between _alTERNAtives_. (As far as I can figure out, there is no etymological connection whatsoever here. The two words go back to Latin _ter_ "three times" and _alter_ "other", but those have completely different reconstructed Proto-Indo-European origins). – hmakholm left over Monica Mar 05 '19 at 16:13
  • A problem here is that the conditional operator isn't quite like other operators. A conditional operator is shorthand for control flow. Also, exactly **one** of the value expressions will be evaluated. – Thomas Bitonti Mar 05 '19 at 16:56
  • 3
    You are right, the OP's expression is not a ternary function, it is a binary function. But the conditional ternary operator is indeed a ternary operator. Just as a = b + 1 is an unary function despite + being a binary operator. The CS expression 'V = X ? Y : Z'. (with X, Y and Z being variables, not constants) can't be expressed as a binary function. – Anonymous Coward Mar 06 '19 at 15:14
  • A lot of the disagreement around this answer seems to stem from confusion over what "This" refers to in "This is not a ternary operator, it is a function of two variables." I submitted an edit to make "This" more explicit, but I don't for sure if I interpreted Ross correctly. – LarsH Mar 06 '19 at 18:36
  • 2
    @Konrad Look a few lines further down: "Although many ternary operators are possible, the conditional operator is so common, and other ternary operators so rare, that the conditional operator is commonly referred to as *the* ternary operator." [emphasis in original] The same article later uses "the ternary operator" without quotation marks: "The ternary operator can also be viewed as a binary map operation." A judgment of "strictly incorrect" would need some justification. – LarsH Mar 06 '19 at 18:40
  • This is incorrect. It is a ternary operator because there are three inputs: the conditional, the value if true, and the value if false. I was going to edit this to fix it, but I feel while it would be correct, it would do violence to the intent of the original author. Instead, see my own answer below. – hackerb9 Mar 07 '19 at 16:36
52

In Concrete Mathematics by Graham, Knuth and Patashnik, the authors use the "Iverson bracket" notation: Square brackets around a statement represent $1$ if the statement is true and $0$ otherwise. Using this notation, you could write $$ a = b + 2 - [c \gt 0]. $$

FredH
  • 4,207
  • 1
  • 14
  • 25
  • 8
    aka https://en.wikipedia.org/wiki/Iverson_bracket – qwr Mar 05 '19 at 06:50
  • @qwr Thank you! I did not recall the name. – FredH Mar 05 '19 at 06:52
  • 10
    I would find it clearer to write $a = b + 1[c>0] + 2[c\le0]$. –  Mar 05 '19 at 07:00
  • 6
    I personally find Iverson brackets less cluttered than indicator functions, so I definitely recommend this notation. – J. M. ain't a mathematician Mar 05 '19 at 12:05
  • 5
    Surely this is a _unary_ operator, which works much like for example `!` in the C programming language: Input is an arbitrary expression, the result is either 0 or 1 depending on the expression. – pipe Mar 05 '19 at 14:46
  • I like this notation! I've been using a less-concise notation for the same, e.g. $\delta_{c > 0}$ rather than $\left[ c > 0 \right] ,$ to stick close to the original Kronecker delta. But if it'll be used a lot, and especially if someone's writing stuff out by hand (who likes to keep writing $`` \delta "$?), this seems like it could be less work. – Nat Mar 05 '19 at 16:15
  • @Rahul: I disagree. I think the notation in the answer is easier to read. – TonyK Mar 06 '19 at 19:41
  • [My comment](https://math.stackexchange.com/questions/3135798/is-there-a-math-equivalent-to-the-conditional-ternary-operator/3136302#comment6464719_3136302) on Nat’s answer also applies here: OK for 1 or 0, clumsy in a ring, fails elsewhere. – PJTraill Mar 06 '19 at 20:25
  • 4
    Interesting note: Iverson, in his original book, used parentheses (x>0) and not brackets [x>0]. Apparently, it was Knuth and Patashnik that converted it into brackets; and they called it the "Iverson bracket". – safkan Mar 07 '19 at 06:49
29

Using the indicator function notation:$$a=b+1+\mathbb{1}_{(-\infty, 0]}(c)$$

Siong Thye Goh
  • 144,233
  • 20
  • 83
  • 146
  • 1
    Indicator is definitely the way to go, since the conditional can define an arbitrary set. – eyeballfrog Mar 05 '19 at 05:47
  • Thank you, that is very elegant. I will definitely try out all of the answers as I often use this in various scenarios. – dataphile Mar 05 '19 at 05:52
  • 2
    I often use - and have seen others use - $\mathbb{1}$ ("blackboard bold") to denote the indicator function to distinguish it from the number $1$ – Christopher Mar 05 '19 at 13:26
  • 1
    The indicator function isn’t a ternary operator, it only has two operands. – Konrad Rudolph Mar 05 '19 at 15:23
  • I don't understand what your indicator means. I've only ever seen indicators used as $1_X$, where $X$ is a true/false-valued expression, so I'd write your indicator as $1_{c<0}$. – David Richerby Mar 07 '19 at 11:50
  • 1
    I used the wikipedia [definition](https://en.wikipedia.org/wiki/Indicator_function), $\mathbb{1}_A(x)$ where $A$ is a set. – Siong Thye Goh Mar 07 '19 at 11:53
17

In math, equations are written in piecewise form by having a curly brace enclose multiple lines; each one with a condition excepting the last which has "otherwise".

There are a few custom operators that also occasionally make an appearance. E.g. the Heavyside function mentioned by Alex, the Dirac function, and the cyclical operator $\delta_{ijk}$ - all of which can be used to emulate conditional behaviour.

Paul Childs
  • 771
  • 3
  • 9
12

I think mathematicians should not be afraid to use the Iverson bracket, including when teaching, as this is a generally very useful notation whose only slightly unusual feature is to introduce a logical expression in the middle of an algebraic one (but one already regularly finds conditions inside set-theoretic expressions, so it really is not a big deal). It may avoid a lot of clutter, notably many instances of clumsy expressions by cases with a big unmatched brace (which is usually only usable as the right hand side of a definition). Since brackets do have many other uses in mathematics, I personally prefer a typographically distinct representation of Iverson brackets, rendering your example as $$\def\[#1]{[\![{#1}]\!]} a= b + \[c>0]1 + \[c\not>0]2. $$ This works best in additive context (though one can use Iverson brackets in the exponent for optional multiplicative factors). It is not really ideal for general two-way branches, as the condition must be repeated twice, one of them in negated form, but it happens that most of the time one needs $0$ as the value for one branch anyway.

As a more concise two-way branch, I can recall that Algol68 introduced the notation $b+(c>0\mid 1\mid 2)$ for the right-hand side of your equation; though this is a programming language and not mathematics, it was designed by mathematicians. They also had notation for multi-way branching: thus the solution to the recursion $a_{n+2}=a_{n+1}-a_n$ with initial values $a_0=0$, $a_1=1$ can be written $$ a_n=(n\bmod 6+1\mid 0,1,1,0,-1,-1) $$ (where the "${}+1$" is needed because in 1968 they still counted starting from $1$, which is a mistake), which is reasonably concise and readable, compared to other ways to express this result. Also consider, for month $m$ in year $y$, the number $$ ( m \mid 31,(y\bmod 4=0\land y\bmod 100\neq0\lor y\bmod400=0\mid 29\mid 28) ,31,30,31,30,31,31,30,31,30,31). $$

Marc van Leeuwen
  • 107,679
  • 7
  • 148
  • 306
  • 1
    So counting months starting from 1 is a mistake? Using matrix indiices starting from 1 (much de rigeur in mathematics) is a mistake? I think the choice made in Algol 68 is based on the very basic concept of counting and cannot be dismissed in such a cavalier way. – Albert van der Horst Aug 17 '19 at 00:47
  • 1
    @AlbertvanderHorst It is of course just an opinion, but yes I do think the using any other number than $0$ (and in particular using $1$) as _default starting value_ for counting is a mistake (I never mentioned counting months in particular, but the general judgement applies). In the sense that it has unnecessary disadvantages (which outweigh and advantages it might have). I believe this is true both in programming and in mathematics, though it is nowadays more accepted in the former. Having $1$-based indexing costs machine cycles, either at runtime, or (with a smart compiler) at compile time. – Marc van Leeuwen Aug 18 '19 at 08:51
  • 1
    ... As for mathematics, there are numerous advantages for indexing from $0$ as a general rule (with exceptions, like for the sequence $(\frac1n)_{n\geq1}$), even though this is not the current convention. I know this from experience as a combinatorist, where I practice indexing from $0$ everywhere, in spite of the drawback of deviating from literature. As an example. consider a Vandermonde matrix; indexing matrices starting from $1$ causes awkwardness in defining them that just does not happen when indexing from $0$. But I do not want to embark on this discussion in these comments. – Marc van Leeuwen Aug 18 '19 at 08:59
  • Good luck with introducing that the general public."I play first fiddle in the London Philharmonic Orchestra." "You main there is some one playing the zeroth fiddle who is more senior". "Why the hell do you thing that???? " "We mathematicians think that if you play first fiddle you actually mean second fiddle." – Albert van der Horst Sep 19 '19 at 18:23
6

The accepted answer from Nat, suggesting the Kronecker Delta, is correct. However, it is also important to note that one of the highly upvoted answers here, which claims the C ternary operator x?y:z is not ternary is incorrect.

Mathematically, the expression x?y:z can be expressed as a function of three variables:
$$f(x,y,z)=\begin {cases} y&x\neq 0\\ z & x=0 \end {cases}$$

Note that in programming an expression such as $a<b$ could be used for $x$. If the expression is true, then $x=1$, otherwise $x=0$.

About nomenclature: computer programmers have used the phrase the ternary operator to mean exactly this since at least the 1970s. Of course, among mathematicians, it would simply be a ternary operator and we would qualify it by either stating a programming language, e.g., the C ternary operator, or by calling it the conditional operator.

hackerb9
  • 168
  • 5
5

One should realize that operators are just a fancy way of using functions. So a ternary operator is a function of 3 variables that is notated in a different way. Is that useful? The answer is mostly not. Also realize that any mathematician is allowed to introduce any notation he feels is illustrative.

Let's review why we use binary operators at all like in a+b*c . Because parameters and results are of the same type, it makes sense to leave out parentheses and introduce complicated priority rules. Imagine that a b c are numbers and we have a normal + and a peculiar * that results in dragons. Now the expression doesn't make sense (assumming a high priority *), because there is no way to add numbers and dragons. Thusly most ternary operators results in a mess.

With a proper notation there are examples of ternary operations. For example, there is a special notation for "sum for i from a to b of expression". This takes two boundaries (numbers) and a function from a number of that type that results in another number. (Mathematician, read "element of an addition group" for number.) The notation for integration is similarly ternary.
So in short ternary operators exist, and you can define your own. They are in general accompagnied with a special notation, or they are not helpful.

Now back to the special case you mention. Because truth values are implied in math, an expression like "if a then b else c" makes sense if a represens a truth value like (7<12). The above expression is understood in every mathematical context. However in a context where truth values are not considered a set, (if .. then .. else ..) would not be considered an operator/function, but a textual explanation. A general accepted notation could be useful in math, but I'm not aware there is one. That is probably, because like in the above, informal notations are readily understood.

3

Fundamentally, the non-answer is the answer. Whatever notation you think you might want to use to express "$a=b+1$ if $c>0$ and $a=b+2$ otherwise" or $$a=\begin{cases}b+1 &\text{if }c>0\\b+2 &\text{otherwise}\end{cases}$$ is much harder to read than either of those two things.

David Richerby
  • 2,420
  • 1
  • 16
  • 24
  • The beauty of formal maths notation is that it expresses identities that can be used to solve / simplify / invert equations without translation to and from a natural language. You are right in a sense, I could just invent a new notation and describe it alongside the equation, but I wouldn't want to reinvent the wheel and risk confusion. – dataphile Mar 07 '19 at 13:59
  • 5
    Most of any mathematics paper _is_ natural language. There's a reason for that. – David Richerby Mar 07 '19 at 15:05
  • Should we put dot (`.`) after `otherwise`? – alper Feb 11 '22 at 12:59
2

There are many good answers that give notation for, “if this condition holds, then 1, else 0.” This corresponds to an even simpler expression in C;(x>1) is equivalent to (x>1 ? 1 : 0).

It’s worth noting that the ternary operator is more general than that. If the arguments are elements of a ring, you could express c ? a : b with (using Iverson-bracket notation) $(a-b) \cdot [c] + b$, but not otherwise. (And compilers frequently use this trick, in a Boolean ring, to compile conditionals without needing to execute a branch instruction.) In a C program, evaluating the expressions $a$ or $b$ might have side-effects, such as deleting a file or printing a message to the screen. In a mathematical function, this isn’t something you would worry about, and a programming language where this is impossible is called functional.

Ross Millikan gave the most standard notation, a cases block. The closest equivalent in mathematical computer science is the if-then-else function of Lambda Calculus.

Davislor
  • 2,528
  • 14
  • 17
  • *"in C;(x>1) is equivalent to (x>1 ? 1 : 0)"* Not exactly. Rather, C considers any nonzero value as equivalent from a truthiness perspective. So there is no difference between an integer expression taking the value of -1, 1, 42 or `INT_MAX` when that expression is treated as a boolean rvalue. In C, the one special integer value, when treated as a boolean, is 0, representing false. That said, if someone actually used `(x>1)` as a non-boolean expression and I noticed it, I would likely at least briefly try to find some heavy physical object that could be applied at high speed to their keyboard. – user Mar 05 '19 at 15:55
  • 1
    @aCVn The C11 standard states, “Each of the operators `<` (less than), `>` (greater than), `<=` (less than or equal to), and `>=` (greater than or equal to) shall yield `1` if the specified relation is true and `0` if it is false.” Similarly for equality and inequality, “Each of the operators yields `1` if the specified relation is true and `0` if it is false.” – Davislor Mar 05 '19 at 16:31
  • @aCVn What you wrote is true, but the relational operators in C will only return the values `1` or `0`. – Davislor Mar 05 '19 at 16:44
  • @aCvn There is nothing wrong with counting how many objects are greater than 10 using n += a[i]>10; . If you don't understand this idiom, you're just a poor c-programmer. – Albert van der Horst Aug 17 '19 at 01:02
  • @AlbertvanderHorst Let’s please be kind. – Davislor Aug 17 '19 at 01:40
  • @aCVn Let's please be kind. In my comment read "If one doesn't understand .. , one is a poor c-programmer.". It was not directed at you personally. – Albert van der Horst Aug 17 '19 at 09:18
  • @AlbertvanderHorst I did not take that comment personally. – user Aug 17 '19 at 09:41
2

Following solution is not defined for $c = 0$; however it uses very basic operations only, which might be useful as you probably look for an expression to implement in a program:

$$a = b + 1\lambda + 2(1-\lambda)$$

where

$$\lambda = \frac{ 1 + \frac{|c|}{c} }{2}$$


You need to make the problem discrete and make a choice from two values. So, given some value $c \in \mathbb{R}$ we need to calculate some value $\lambda \in \{0,1\}$ depnding on $c<0$ or $c>0$.

Knowing that

$$\frac{|c|}{c} \in \{1,-1\}$$

we can calculate the $\lambda$ as follows:

$$\lambda = \frac{ 1 + \frac{|c|}{c} }{2}$$

Now that our $\lambda \in \{0,1\}$ we can do the "choice" between the two constants $d$ and $e$ as follows:

$$d\lambda + e(1-\lambda)$$

which equals $d$ for $\lambda = 1$, and $e$ for $\lambda = 0$.

Timur
  • 129
  • 3
2

The best idea is probably to split the world into different cases above the context in which your expression lives, so you consider the cases where $c$ is positive and the cases where $c$ is nonpositive separately. Or impose conditions on $c$ like $|c| = 1$ .

Another alternative is to create some new ad hoc indicator-like functions whose algebraic properties are as strong as possible. I'm partial to signum because it's odd and multiplicative.

b + (c > 0 ? 1 : 2)

Can be written nicely using two new functions $S$ for signum and $Z$ the zero indicator function:

$$ S(x) \stackrel{\small{\text{def}}}{=} \begin{cases} \;\;1 & x > 0 \\ \;\;0 & x = 0 \\ -1 & x < 0 \end{cases}$$

And $Z$ is $1$ when its argument is $0$ and $0$ otherwise.

So we can write the expression as

$$ b + \frac{3}{2} + \frac{1}{2} S(c) - \frac{1}{2} Z(c) $$

or

$$ b + 1 + S(c) + \frac{1}{2} S^2(c) $$

with $S^2(c)$ denoting $S(c^2)$ or $S(c)^2$ since they're equivalent.

This expression isn't that great in this case, but $S$ and $Z$ have some nice properties:

$$ S(a)S(b) = S(ab) $$ $$ S(a)Z(a) = 0 $$ $$ Z(a) = 1 - S(a)^2 $$ $$ S(S(a)) = S(a) $$ $$ S(a)^n = S(a^n) \;\;\;\;\forall n \in \mathbb{N} $$ $$ S(a)^m = S(a)^m \cdot S(a)^{(2n)} \;\;\;\;\forall m, n \in \mathbb{N} $$

Greg Nisbet
  • 6,712
  • 3
  • 13
  • 29
2

The concepts from lambda calculus and combinatory logic is worth mentioning here.

We define lambda calculus by two constructions: - you can make a function using abstraction, e.g. to define the function $f(x)=x+1$ (assuming that numbers and addition is defined), we write $\lambda x.x+1$. - you can use a function using application, e.g. given a function $M$, we can evaluate it at $x$ by $M\ x$.

Surprisingly, these two constructions are enough to express all of mathematics, without anything else assumed! For natural numbers, there is Church numerals to use. To define boolean values, we can write $$\mathbf{True} \equiv \lambda x. \lambda y. x$$ and $$\mathbf{False} \equiv \lambda x. \lambda y. y.$$ From this we can define all of Boolean algebra. Specifically, for the tenary operator $b?x:y$, we can construct the expression $b\ x\ y.$

Trebor
  • 3,044
  • 1
  • 7
  • 27
  • Very interesting. Being Turing-complete this where math and computers meet. I'll look into this further. – dataphile Mar 13 '19 at 05:03
1

For mathematical logic, let's say that the ternary operator A ? B : C represents "for the predicates $A$, $B$, $C$, if $B$ is true iff $A$ is true, and $C$ is true iff $A$ is false". We can then represent your problem as $A := (c > 0)$, $B := (a = b + 1)$, and $C := (a = b + 2)$. We can write this in predicate logic as the true statement

$$(\neg A \iff C) \land (A \iff B)$$

We can verify the correctness of this with a truth table:

$$\begin{array} {|c c c | c |} \hline A & B & C & (\neg A \iff C) \land (A \iff B) \\ \hline F & F & F & F \\ \hline F & F & T & \color{blue}T \\ \hline F & T & F & F \\ \hline F & T & T & F \\ \hline T & F & F & F \\ \hline T & F & T & F \\ \hline T & T & F & \color{blue}T \\ \hline T & T & T & F \\ \hline \end{array} $$