Number
int64
1
7.61k
Text
stringlengths
2
3.11k
4,301
Some argue that the explicit if/then statement is easier to read and that it may compile to more efficient code than the ternary operator, while others argue that concise expressions are easier to read than statements spread over several lines containing repetition.
4,302
First, when the user runs the program, a cursor appears waiting for the reader to type a number. If that number is greater than 10, the text "My variable is named 'foo'." is displayed on the screen. If the number is smaller than 10, then the message "My variable is named 'bar'." is printed on the screen.
4,303
In Visual Basic and some other languages, a function called IIf is provided, which can be used as a conditional expression. However, it does not behave like a true conditional expression, because both the true and false branches are always evaluated; it is just that the result of one of them is thrown away, while the result of the other is returned by the IIf function.
4,304
In Tcl if is not a keyword but a function . For example
4,305
invokes a function named if passing 2 arguments: The first one being the condition and the second one being the true branch. Both arguments are passed as strings .
4,306
In the above example the condition is not evaluated before calling the function. Instead, the implementation of the if function receives the condition as a string value and is responsible to evaluate this string as an expression in the callers scope.
4,307
Such a behavior is possible by using uplevel and expr commands:
4,308
Because if is actually a function it also returns a value:
4,309
In Rust, if is always an expression. It evaluates to the value of whichever branch is executed, or to the unit type if no branch is executed. If a branch does not provide a return value, it evaluates to by default. To ensure the if expression's type is known at compile time, each branch must evaluate to a value of the same type. For this reason, an else branch is effectively compulsory unless the other branches evaluate to , because an if without an else can always evaluate to by default.
4,310
Up to Fortran 77, the language Fortran has an "arithmetic if" statement which is halfway between a computed IF and a case statement, based on the trichotomy x < 0, x = 0, x > 0. This was the earliest conditional statement in Fortran:
4,311
Where e is any numeric expression ; this is equivalent to
4,312
Because this arithmetic IF is equivalent to multiple GOTO statements that could jump to anywhere, it is considered to be an unstructured control statement, and should not be used if more structured statements can be used. In practice it has been observed that most arithmetic IF statements referenced the following statement with one or two of the labels.
4,313
This was the only conditional control statement in the original implementation of Fortran on the IBM 704 computer. On that computer the test-and-branch op-code had three addresses for those three states. Other computers would have "flag" registers such as positive, zero, negative, even, overflow, carry, associated with the last arithmetic operations and would use instructions such as 'Branch if accumulator negative' then 'Branch if accumulator zero' or similar. Note that the expression is evaluated once only, and in cases such as integer arithmetic where overflow may occur, the overflow or carry flags would be considered also.
4,314
In contrast to other languages, in Smalltalk the conditional statement is not a language construct but defined in the class Boolean as an abstract method that takes two parameters, both closures. Boolean has two subclasses, True and False, which both define the method, True executing the first closure only, False executing the second closure only.
4,315
JavaScript uses if-else statements similar to those in C languages. A Boolean value is accepted within parentheses between the reserved if keyword and a left curly bracket.
4,316
The above example takes the conditional of Math.random < 0.5 which outputs true if a random float value between 0 and 1 is greater than 0.5. The statement uses it to randomly choose between outputting You got Heads! or You got Tails! to the console. Else and else-if statements can also be chained after the curly bracket of the statement preceding it as many times as necessary, as shown below:
4,317
In Lambda calculus, the concept of an if-then-else conditional can be expressed using the following expressions:
4,318
true takes up to two arguments and once both are provided , it returns the first argument given.
4,319
false takes up to two arguments and once both are provided, it returns the second argument given.
4,320
ifThenElse takes up to three arguments and once all are provided, it passes both second and third argument to the first argument. We expect ifThenElse to only take true or false as an argument, both of which project the given two arguments to their preferred single argument, which is then returned.
4,321
note: if ifThenElse is passed two functions as the left and right conditionals; it is necessary to also pass an empty tuple to the result of ifThenElse in order to actually call the chosen function, otherwise ifThenElse will just return the function object without getting called.
4,322
In a system where numbers can be used without definition , the above can be expressed as a single closure below:
4,323
Here, true, false, and ifThenElse are bound to their respective definitions which are passed to their scope at the end of their block.
4,324
A working JavaScript analogy to this is as follows:
4,325
The code above with multivariable functions looks like this:
4,326
Another version of the earlier example without a system where numbers are assumed is below.
4,327
The first example shows the first branch being taken, while second example shows the second branch being taken.
4,328
Smalltalk uses a similar idea for its true and false representations, with True and False being singleton objects that respond to messages ifTrue/ifFalse differently.
4,329
Haskell used to use this exact model for its Boolean type, but at the time of writing, most Haskell programs use syntactic sugar "if a then b else c" construct which unlike ifThenElse does not compose unless either wrapped in another function or re-implemented as shown in The Haskell section of this page.
4,330
Switch statements compare a given value with specified constants and take action according to the first constant to match. There is usually a provision for a default action to be taken if no match succeeds. Switch statements can allow compiler optimizations, such as lookup tables. In dynamic languages, the cases may not be limited to constant expressions, and might extend to pattern matching, as in the shell script example on the right, where the '*)' implements the default case as a regular expression matching any string.
4,331
Pattern matching may be seen as an alternative to both if–then–else, and case statements. It is available in many programming languages with functional programming features, such as Wolfram Language, ML and many others. Here is a simple example written in the OCaml language:
4,332
The power of pattern matching is the ability to concisely match not only actions but also values to patterns of data. Here is an example written in Haskell which illustrates both of these features:
4,333
This code defines a function map, which applies the first argument to each of the elements of the second argument , and returns the resulting list. The two lines are the two definitions of the function for the two kinds of arguments possible in this case – one where the list is empty and the other case where the list is not empty.
4,334
Pattern matching is not strictly speaking always a choice construct, because it is possible in Haskell to write only one alternative, which is guaranteed to always be matched – in this situation, it is not being used as a choice construct, but simply as a way to bind names to values. However, it is frequently used as a choice construct in the languages in which it is available.
4,335
In programming languages that have associative arrays or comparable data structures, such as Python, Perl, PHP or Objective-C, it is idiomatic to use them to implement conditional assignment.
4,336
In languages that have anonymous functions or that allow a programmer to assign a named function to a variable reference, conditional flow can be implemented by using a hash as a dispatch table.
4,337
An alternative to conditional branch instructions is predication. Predication is an architectural feature that enables instructions to be conditionally executed instead of modifying the control flow.
4,338
This table refers to the most recent language specification of each language. For languages that do not have a specification, the latest officially released implementation is referred to.
4,339
An operand of a negation is a negand, or negatum.
4,340
The truth table of ¬ P {\displaystyle \neg P} is as follows:
4,341
Algebraically, classical negation corresponds to complementation in a Boolean algebra, and intuitionistic negation to pseudocomplementation in a Heyting algebra. These algebras provide a semantics for classical and intuitionistic logic.
4,342
The negation of a proposition p is notated in different ways, in various contexts of discussion and fields of application. The following table documents some of these variants:
4,343
Here is a table that shows a commonly used precedence of logical operators.
4,344
As a result, in the propositional case, a sentence is classically provable if its double negation is intuitionistically provable. This result is known as Glivenko's theorem.
4,345
De Morgan's laws provide a way of distributing negation over disjunction and conjunction:
4,346
Another way to express this is that each variable always makes a difference in the truth-value of the operation, or it never makes a difference. Negation is a linear logical operator.
4,347
In Boolean algebra, a self dual function is a function such that:
4,348
As in mathematics, negation is used in computer science to construct logical statements.
4,349
The exclamation mark "!" signifies logical NOT in B, C, and languages with a C-inspired syntax such as C++, Java, JavaScript, Perl, and PHP. "NOT" is the operator used in ALGOL 60, BASIC, and languages with an ALGOL- or BASIC-inspired syntax such as Pascal, Ada, Eiffel and Seed7. Some languages provide more than one operator for negation. A few languages like PL/I and Ratfor use ¬ for negation. Most modern languages allow the above statement to be shortened from if ) to if , which allows sometimes, when the compiler/interpreter is not able to optimize it, faster programs.
4,350
In computer science there is also bitwise negation. This takes the value given and switches all the binary 1s to 0s and 0s to 1s. See bitwise operation. This is often used to create ones' complement or "~" in C or C++ and two's complement as it basically creates the opposite or mathematical complement of the value .
4,351
To get the absolute value of a given integer the following would work as the "-" changes it from negative to positive
4,352
To demonstrate logical negation:
4,353
Inverting the condition and reversing the outcomes produces code that is logically equivalent to the original code, i.e. will have identical results for any input .
4,354
This convention occasionally surfaces in ordinary written speech, as computer-related slang for not. For example, the phrase !voting means "not voting". Another example is the phrase !clue which is used as a synonym for "no-clue" or "clueless".
4,355
In Kripke semantics where the semantic values of formulae are sets of possible worlds, negation can be taken to mean set-theoretic complementation .
4,356
It gains the name "exclusive or" because the meaning of "or" is ambiguous when both operands are true. XOR excludes that case. Some informal ways of describing XOR are "one or the other but not both", "either one or the other", and "A or B, but not A and B".
4,357
or:
4,358
This equivalence can be established by applying De Morgan's laws twice to the fourth line of the above proof.
4,359
The exclusive or is also equivalent to the negation of a logical biconditional, by the rules of material implication and material equivalence.
4,360
In summary, we have, in mathematical and in engineering notation:
4,361
The spirit of De Morgan's laws can be applied, we have:
4,362
Disjunction is often understood exclusively in natural languages. In English, the disjunctive word "or" is often understood exclusively, particularly when used with the particle "either". The English example below would normally be understood in conversation as implying that Mary is not both a singer and a poet.
4,363
However, disjunction can also be understood inclusively, even in combination with "either". For instance, the first example below shows that "either" can be felicitously used in combination with an outright statement that both disjuncts are true. The second example shows that the exclusive inference vanishes away under downward entailing contexts. If disjunction were understood as exclusive in this example, it would leave open the possibility that some people ate both rice and beans.
4,364
Examples such as the above have motivated analyses of the exclusivity inference as pragmatic conversational implicatures calculated on the basis of an inclusive semantics. Implicatures are typically cancellable and do not arise in downward entailing contexts if their calculation depends on the Maxim of Quantity. However, some researchers have treated exclusivity as a bona fide semantic entailment and proposed nonclassical logics which would validate it.
4,365
This behavior of English "or" is also found in other languages. However, many languages have disjunctive constructions which are robustly exclusive such as French soit... soit.
4,366
The symbol used for exclusive disjunction varies from one field of application to the next, and even depends on the properties being emphasized in a given context of discussion. In addition to the abbreviation "XOR", any of the following symbols may also be seen:
4,367
If using binary values for true and false , then exclusive or works exactly like addition modulo 2.
4,368
Exclusive disjunction is often used for bitwise operations. Examples:
4,369
In computer science, exclusive disjunction has several uses:
4,370
In logical circuits, a simple adder can be made with an XOR gate to add the numbers, and a series of AND, OR and NOT gates to create the carry output.
4,371
On some computer architectures, it is more efficient to store a zero in a register by XOR-ing the register with itself than to load and store the value zero.
4,372
In cryptography, XOR is sometimes used as a simple, self-inverse mixing function, such as in one-time pad or Feistel network systems. XOR is also heavily used in block ciphers such as AES or Serpent and in block cipher implementation .
4,373
In simple threshold-activated artificial neural networks, modeling the XOR function requires a second layer because XOR is not a linearly separable function.
4,374
Similarly, XOR can be used in generating entropy pools for hardware random number generators. The XOR operation preserves randomness, meaning that a random bit XORed with a non-random bit will result in a random bit. Multiple sources of potentially random data can be combined using XOR, and the unpredictability of the output is guaranteed to be at least as good as the best individual source.
4,375
XOR is used in RAID 3–6 for creating parity information. For example, RAID can "back up" bytes 100111002 and 011011002 from two hard drives by XORing the just mentioned bytes, resulting in and writing it to another drive. Under this method, if any one of the three hard drives are lost, the lost byte can be re-created by XORing bytes from the remaining drives. For instance, if the drive containing 011011002 is lost, 100111002 and 111100002 can be XORed to recover the lost byte.
4,376
XOR is also used to detect an overflow in the result of a signed binary arithmetic operation. If the leftmost retained bit of the result is not the same as the infinite number of digits to the left, then that means overflow occurred. XORing those two bits will give a "1" if there is an overflow.
4,377
XOR can be used to swap two numeric variables in computers, using the XOR swap algorithm; however this is regarded as more of a curiosity and not encouraged in practice.
4,378
XOR linked lists leverage XOR properties in order to save space to represent doubly linked list data structures.
4,379
In computer graphics, XOR-based drawing methods are often used to manage such items as bounding boxes and cursors on systems without alpha channels or overlay planes.
4,380
An operand of a disjunction is a disjunct.
4,381
Because the logical "or" means a disjunction formula is true when either one or both of its parts are true, it is referred to as an inclusive disjunction. This is in contrast with an exclusive disjunction, which is true when one or the other of the arguments are true, but not both .
4,382
When it is necessary to clarify whether inclusive or exclusive "or" is intended, English speakers sometimes uses the phrase "and/or". In terms of logic, this phrase is identical to "or", but makes the inclusion of both being true explicit.
4,383
In the semantics of logic, classical disjunction is a truth functional operation which returns the truth value "true" unless both of its arguments are "false". Its semantic entry is standardly given as follows:
4,384
This semantics corresponds to the following truth table:
4,385
The latter can be checked by the following truth table:
4,386
It can be checked by the following truth table:
4,387
The following properties apply to disjunction:
4,388
Operators corresponding to logical disjunction exist in most programming languages.
4,389
Disjunction is often used for bitwise operations. Examples:
4,390
The or operator can be used to set bits in a bit field to 1, by or-ing the field with a constant field with the relevant bits set to 1. For example, x = x | 0b00000001 will force the final bit to 1, while leaving other bits unchanged.
4,391
Many languages distinguish between bitwise and logical disjunction by providing two distinct operators; in languages following C, bitwise disjunction is performed with the single pipe operator , and logical disjunction with the double pipe operator.
4,392
Logical disjunction is usually short-circuited; that is, if the first operand evaluates to true, then the second operand is not evaluated. The logical disjunction operator thus usually constitutes a sequence point.
4,393
In a parallel language, it is possible to short-circuit both sides: they are evaluated in parallel, and if one terminates with value true, the other is interrupted. This operator is thus called the parallel or.
4,394
Although the type of a logical disjunction expression is boolean in most languages , in some languages , the logical disjunction operator returns one of its operands: the first operand if it evaluates to a true value, and the second operand otherwise.
4,395
The Curry–Howard correspondence relates a constructivist form of disjunction to tagged union types.
4,396
This inference has sometimes been understood as an entailment, for instance by Alfred Tarski, who suggested that natural language disjunction is ambiguous between a classical and a nonclassical interpretation. More recent work in pragmatics has shown that this inference can be derived as a conversational implicature on the basis of a semantic denotation which behaves classically. However, disjunctive constructions including Hungarian vagy... vagy and French soit... soit have been argued to be inherently exclusive, rendering ungrammaticality in contexts where an inclusive reading would otherwise be forced.
4,397
Similar deviations from classical logic have been noted in cases such as free choice disjunction and simplification of disjunctive antecedents, where certain modal operators trigger a conjunction-like interpretation of disjunction. As with exclusivity, these inferences have been analyzed both as implicatures and as entailments arising from a nonclassical interpretation of disjunction.
4,398
In many languages, disjunctive expressions play a role in question formation. For instance, while the following English example can be interpreted as a polar question asking whether it's true that Mary is either a philosopher or a linguist, it can also be interpreted as an alternative question asking which of the two professions is hers. The role of disjunction in these cases has been analyzed using nonclassical logics such as alternative semantics and inquisitive semantics, which have also been adopted to explain the free choice and simplification inferences.
4,399
In English, as in many other languages, disjunction is expressed by a coordinating conjunction. Other languages express disjunctive meanings in a variety of ways, though it is unknown whether disjunction itself is a linguistic universal. In many languages such as Dyirbal and Maricopa, disjunction is marked using a verb suffix. For instance, in the Maricopa example below, disjunction is marked by the suffix šaa.
4,400
John-NOM