Ternary operation
Encyclopedia
In mathematics
Mathematics
Mathematics is the study of quantity, space, structure, and change. Mathematicians seek out patterns and formulate new conjectures. Mathematicians resolve the truth or falsity of conjectures by mathematical proofs, which are arguments sufficient to convince other mathematicians of their validity...

, a ternary operation is an n-ary operation with n = 3. A ternary operation on a set A takes any given three elements of A and combines them to form a single element of A. An example of a ternary operation is the product in a heap
Heap (mathematics)
In abstract algebra, a heap is a mathematical generalisation of a group. Informally speaking, a heap is obtained from a group by "forgetting" which element is the unit, in the same way that an affine space can be viewed as a vector space in which the 0 element has been "forgotten"...

.

In computer science
Computer science
Computer science or computing science is the study of the theoretical foundations of information and computation and of practical techniques for their implementation and application in computer systems...

, a ternary operator (sometimes incorrectly called a tertiary operator) is an operator
Operator (programming)
Programming languages typically support a set of operators: operations which differ from the language's functions in calling syntax and/or argument passing mode. Common examples that differ by syntax are mathematical arithmetic operations, e.g...

 that takes three arguments. The arguments and result can be of different types.

Many programming languages that use C-like syntax
C syntax
The syntax of the C programming language is a set of rules that specifies whether the sequence of characters in a file is conforming C source code...

 feature a ternary operator, ?:
?:
In computer programming, ?: is a ternary operator that is part of the syntax for a basic conditional expression in several programming languages...

, which defines a conditional expression. Since this operator is often the only existing ternary operator in the language, it is sometimes simply referred to as "the ternary operator", though it is more accurately referred to as the conditional operator.

Most of the languages emphasizing functional programming
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...

 don't need such an operator as their regular conditional expression(s) is an expression in the first place e.g. the Scheme expression (if (> a b) a b) is equivalent in semantics to the C expression (a > b) ? a : b. This is also the case in many imperative languages, starting with ALGOL
ALGOL
ALGOL is a family of imperative computer programming languages originally developed in the mid 1950s which greatly influenced many other languages and became the de facto way algorithms were described in textbooks and academic works for almost the next 30 years...

 where it is possible to write result := if a > b then a else b, or Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...

 (result := (a > b) ifTrue: [ a ] ifFalse: [ b ]) or Ruby (result = if a > b: a else b end)

C, C++, C#, Vala, Objective-C, Java, JavaScript, ActionScript

A traditional if-else construct in C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

, C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

, C#, Vala
Vala (programming language)
Vala is a programming language created with the goal of bringing modern language features to C, with no added runtime needs and with little overhead, by targeting the GObject object system. It is being developed by Jürg Billeter and Raffaele Sandrini. The syntax borrows heavily from C#...

, Objective-C
Objective-C
Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it...

, Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

, JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

 and ActionScript
ActionScript
ActionScript is an object-oriented language originally developed by Macromedia Inc. . It is a dialect of ECMAScript , and is used primarily for the development of websites and software targeting the Adobe Flash Player platform, used on Web pages in the form of...

 is written:

if (a > b) {
result = x;
}
else {
result = y;
}


This can be rewritten as the following ternary statement:


result = a > b ? x : y;

Common Lisp

Assignment using a ternary expression in Common Lisp
Common Lisp
Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers...

:

(setf result (if (> a b) x y))


Imperative form:

(if (> a b)
(setf result x)
(setf result y))

Perl, PHP

A traditional if-else construct in Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

 or PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

 is written:

if ($a > $b) {
$result = $x;
} else {
$result = $y;
}

Rewritten to use the ternary operator:

$result = ($a > $b) ? $x : $y;

Perl 6

Uses double "?" symbols and double "!" instead of ":" :

$result = ($a > $b) ?? $x !! $y;

Python

Though it had been delayed for several years by disagreements over syntax, a ternary operator for Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

 was approved as Python Enhancement Proposal 308 and was added to the 2.5 release in September 2006. Python's ternary operator differs from the common ?: operator in the order of its operands. The general form is:

x if a > b else y

This form invites considering x as the normal value and y as an exceptional case. One can use the syntax (lambda:y, lambda:x)[a > b] as a workaround for code that also needs to run under Python versions before 2.5. Note that operands are lazily evaluated
Lazy evaluation
In programming language theory, lazy evaluation or call-by-need is an evaluation strategy which delays the evaluation of an expression until the value of this is actually required and which also avoids repeated evaluations...

, it is possible to remove the lambdas and function calls but the operands will be eagerly evaluated which isn't consistent with other languages' ternary operators, e.g. by using an explicitly constructed dictionary:
{True: x, False: y}[a > b]

A less reliable but simpler to read alternative is to abuse the and and or operators and write
(a > b) and x or y
but this code would break if x could be a "falsy" value (None, False, 0, an empty sequence or collection, …) as the expression would return y (whether it was truthy or falsy) instead of the (falsy) x.
A possible workaround is to make x and y lists or tuples, so they are never falsy, and then grab the first element of the resulting sequence as in the following
((a > b) and [x] or [y])[0] or ((a > b) and (x,) or (y,))[0]

Ruby

A traditional if-else construct in Ruby
Ruby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...

 is written:

if a > b
result = x
else
result = y
end


This could also be written as:

result = if a > b
x
else
y
end


These can be rewritten as the following ternary statement:


result = a > b ? x : y

Visual Basic

Visual Basic
Visual Basic .NET
Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework...

 Version 9 has added a ternary operator, If, in addition to the existing IIf function that existed previously. As a true operator, it does not have the side effects and potential inefficiencies of the IIf function.

The syntaxes of the tokens are similar: If([condition,] op1, op2) vs IIf(condition, op1, op2). As mentioned above, the function call has significant disadvantages, because the sub-expressions must all be evaluated, according to Visual Basic's evaluation strategy
Evaluation strategy
In computer science, an evaluation strategy is a set of rules for evaluating expressions in a programming language. Emphasis is typically placed on functions or operators: an evaluation strategy defines when and in what order the arguments to a function are evaluated, when they are substituted...

 for function calls and the result will always be of type variant (VB) or object (VB.NET). The Ifoperator however does not suffer from these problems as it supports conditional evaluation and determines the type of the expression based on the types of its operands.

PL/SQL

A specific ternary operator for PL/SQL
PL/SQL
PL/SQL is Oracle Corporation's procedural extension language for SQL and the Oracle relational database...

 is not available, but a special case of the CASE expression works exactly as a ternary operator:


SELECT (CASE WHEN a > b THEN x ELSE y END) AS "Ternary_Example"
FROM DUAL;

External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK