Elvis operator

In certain computer programming languages, the Elvis operator, often written ?:, or or ||, is a binary operator that returns its first operand if that operand evaluates to a true value, and otherwise evaluates and returns its second operand. The Elvis operator is a variant of the ternary conditional operator, ? : in the sense that the expression with the Elvis operator A ?: B is approximately equivalent to the expression with the ternary operator A ? A : B.

The name "Elvis operator" refers to the fact that when its common notation, ?:, is viewed sideways, it resembles an emoticon of Elvis Presley with his quiff.[1]

A similar operator is the null coalescing operator, where the check for boolean truthiness is replaced with a check for non-null instead. This is usually written ??, and can be seen in languages like C#.[2]

Example

Boolean variant

In a language that supports the Elvis operator, something like this:

x = f() ?: g()

will set x equal to the result of f() if that result is a true value, and to the result of g() otherwise.

It is equivalent to this example, using the conditional ternary operator:

x = f() ? f() : g()

except that it does not evaluate the f() twice if it is true.

Object reference variant

This code will result in a reference to an object that is guaranteed to not be null. Function f() returns an object reference instead of a boolean, and may return null:

x = f() ?: "default value"

Languages supporting the Elvis operator

  • In GNU C and C++ (that is: in C and C++ with GCC extensions), the second operand of the ternary operator is optional.[3] This has been the case since at least GCC 2.95.3 (March 2001), and seems to the original elvis operator.[4]
  • In Apache Groovy, the "Elvis operator" ?: is documented as a distinct operator;[5] this feature was added in Groovy 1.5[6] (December 2007). Groovy, unlike GNU C and PHP, does not simply allow the second operand of ternary ?: to be omitted; rather, binary ?: must be written as a single operator, with no whitespace in between.
  • In PHP, it is possible to leave out the middle part of the ternary operator since PHP 5.3.[7] (June 2009).
  • The Fantom programming language has the ?: binary operator that compares its first operand with null.
  • In Kotlin, the Elvis operator returns its left-hand side if it is not null, and its right-hand side otherwise.[8] A common pattern is to use it with return, like this: val foo = bar() ?: return
  • In Gosu, the ?: operator returns the right operand if the left is null as well.
  • In C#, the null-conditional operator, ?. is referred to as the "Elvis operator",[9] but it does not perform the same function. Instead, the null-coalescing operator ?? does.
  • In ColdFusion and CFML, the Elvis operator was introduced using the ?: syntax.
  • The Xtend programming language has an Elvis operator.[10]
  • In Google's Closure Templates, the Elvis operator is a null coalescing operator, equivalent to isNonnull($a) ? $a : $b.[11]
  • Swift supports this concept with its Nil-coalescing operator ??,[12] e.g. (a ?? b).
  • SQL supports this concept with its COALESCE function, e.g. COALESCE(a, b).
  • In Ballerina, the Elvis operator L ?: R returns the value of L if it's not nil. Otherwise, return the value of R.[13]
  • Clojure supports this concept with the or[14] macro, e.g. (or a b). In the case of Clojure, it is var-arg, and not binary, e.g. (or a b c d e) will return the first non false value.
  • Dart language provides ?? operator which returns right side value if left side value is null
  • TypeScript supports this concept with its nullish-coalescing operator ??, e.g. (a ?? b), since v3.7.[15]

Analogous use of the short-circuiting OR operator

In several languages, such as Common Lisp, Clojure, Lua, Perl, Python, Ruby, and JavaScript, the OR operator (typically || or or) has the same behavior as the above: returning its first operand if it would evaluate to true in a boolean environment, and otherwise evaluating and returning its second operand. When the left hand side is true, the right hand side is not even evaluated; it is "short-circuited."

gollark: Idea: Make an esolang based around ideas for esolangs.
gollark: https://aphyr.com/posts/342-typing-the-technical-interview
gollark: If this worked as expected, in theory you could do```pythonraise quibble("abcd")```but alas, no.
gollark: But which runs much faster.
gollark: ```pythonfrom requests_futures.sessions import FuturesSessionimport concurrent.futures as futuresimport randomtry: import cPickle as pickleexcept ImportError: import pickletry: words_to_synonyms = pickle.load(open(".wtscache")) synonyms_to_words = pickle.load(open(".stwcache"))except: words_to_synonyms = {} synonyms_to_words = {}def add_to_key(d, k, v): d[k] = d.get(k, set()).union(set(v))def add_synonyms(syns, word): for syn in syns: add_to_key(synonyms_to_words, syn, [word]) add_to_key(words_to_synonyms, word, syns)def concat(list_of_lists): return sum(list_of_lists, [])def add_words(words): s = FuturesSession(max_workers=100) future_to_word = {s.get("https://api.datamuse.com/words", params={"ml": word}): word for word in words} future_to_word.update({s.get("https://api.datamuse.com/words", params={"ml": word, "v": "enwiki"}): word for word in words}) for future in futures.as_completed(future_to_word): word = future_to_word[future] try: data = future.result().json() except Exception as exc: print(f"{exc} fetching {word}") else: add_synonyms([w["word"] for w in data], word)def getattr_hook(obj, key): results = list(synonyms_to_words.get(key, set()).union(words_to_synonyms.get(key, set()))) if len(results) > 0: return obj.__getattribute__(random.choice(results)) else: raise AttributeError(f"Attribute {key} not found.")def wrap(obj): add_words(dir(obj)) obj.__getattr__ = lambda key: getattr_hook(obj, key)wrap(__builtins__)print(words_to_synonyms["Exception"])```New version which tends to reduce weirder output.

See also

References

  1. Joyce Farrell. Java Programming. p. 276. ISBN 978-1285081953. The new operator is called Elvis operator because it uses a question mark and a colon together (?:); if you view it sideways, it reminds you of Elvis Presley.
  2. "?? Operator". C# Reference. Microsoft. Retrieved 5 December 2018.
  3. "Using the GNU Compiler Collection (GCC): Conditionals". gcc.gnu.org.
  4. "Using and Porting the GNU Compiler Collection (GCC): C Extensions". gcc.gnu.org.
  5. "Elvis Operator (?: )".
  6. "The Apache Groovy programming language - Groovy 1.5 release notes". groovy-lang.org.
  7. "PHP: Comparison Operators - Manual". PHP website. Retrieved 2014-02-17.
  8. "Null Safety - Kotlin Programming Language". Kotlin.
  9. Albahari, Joseph; Albahari, Ben (2015). C# 6.0 in a Nutshell (6 ed.). O'Reilly Media. p. 59. ISBN 978-1491927069.
  10. Efftinge, Sven. "Xtend - Expressions". eclipse.org.
  11. "Closure Templates - Expressions". GitHub.
  12. "The Swift Programming Language (Swift 4.1): Basic Operators". developer.apple.com.
  13. "Elvis Operator - Ballerina Programming Language". Ballerina.
  14. "clojure.core or macro API reference".
  15. "nullish coalescing commit by Kingwl · Pull Request #32883 · microsoft/TypeScript". GitHub. Retrieved 2019-10-08.
This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.