Boolean values: Difference between revisions
No edit summary |
|||
Line 404: | Line 404: | ||
The only values in Ruby that are false are: <code>false</code> and <code>nil</code>. They have synonyms <code>FALSE</code> and <code>NIL</code>. |
The only values in Ruby that are false are: <code>false</code> and <code>nil</code>. They have synonyms <code>FALSE</code> and <code>NIL</code>. |
||
Everything else ( |
Everything else is true. Constants <code>true</code> (and <code>TRUE</code>) exist. Note for Python and Perl users: unlike Python, in Ruby, the number <code>0</code>, the empty string, the empty array, and the empty hash, etc. are all true; you can instead use the <code>zero?</code> method to test for 0, and the <code>.empty?</code> method to test for an empty sequence. |
||
<code>false</code>, <code>nil</code> and <code>true</code> are singleton instances of classes <code>FalseClass</code>, <code>NilClass</code> and <code>TrueClass</code> respectively. |
<code>false</code>, <code>nil</code> and <code>true</code> are singleton instances of classes <code>FalseClass</code>, <code>NilClass</code> and <code>TrueClass</code> respectively. |
Revision as of 19:00, 15 March 2010
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. (See also: Logical operations)
Ada
Ada has a predefined discrete type with the specification: <lang Ada> type Boolean is (False, True);</lang> with Boolean lattice and relational operations defined on it. See RM A.1.
AutoHotkey
When an expression is required to evaluate to true or false (such as an IF-statement), a blank or zero result is considered false and all other results are considered true. Operators such as NOT/AND/OR/>/=/< automatically produce a true or false value: they yield 1 for true and 0 for false. A variable can be used to hold a false value simply by making it blank or assigning 0 to it. The words 'true' and 'false' are built-in variables containing 1 and 0. They can be used to make a script more readable.
AWK
In awk, any nonzero numeric value or any nonempty string value is true. Any other value (zero or the null string "") is false. [...] the string constant "0" is actually true, because it is non-null. [1]
AppleScript
AppleScript has built-in boolean keywords true
and false
. Numbers do not work in place of boolean expressions.
BASIC
Most BASICs have no keywords for true and false. Boolean expressions evaluate to 0 when false, and a non-zero value (default of negative one) when true. Numbers also work in place of boolean expressions following those rules.
Befunge
Zero is false, non-zero is true. This is only used by the horizontal and vertical switch operators (_ and |).
Brainf***
Zero is false, non-zero is true. This is only used by the loop brackets ([ and ]).
C
In C, a value which is equal to 0 is false, while a value which is not equal to 0 is true. Relational and logical operators evaluate to 0 for false and 1 for true. Any of the following can be used:
- any integer type, where 0 gives false, and any other value gives true (note that in C, character types are also integer types, therefore this also applies to characters: the
'\0'
character is false) - any floating point type, where again, 0 gives false and everything else gives true
- any enumeration type, again 0 gives false, anything else true
- any pointer type, where the null pointer gives false and any other pointer gives true
- in C99, the boolean type
bool
(defined in header <stdbool.h>), wheretrue
gives true andfalse
gives false - in C99, any complex number type, where 0 (0 real and 0 imaginary) gives false, anything else gives true
C++
In C++, there are the constants true
and false
to represent those values. However, there are numerous implicit conversions to bool
, therefore in conditions (and other contexts expecting boolean values), any of the following can be used:
- any integer type, where 0 converts to false, and any other value converts to true (note that in C++, character types are also integer types, therefore this also applies to characters: the
'\0'
character is false) - any floating point type, where again, 0 gives false and everything else gives true
- any enumeration type, again 0 gives false, anything else true
- any pointer type, where the null pointer gives false and any other pointer gives true
- any user-defined type with an implicit conversion operator either to
bool
or to a built-in type which itself can be converted tobool
(i.e. any of the above). The C++ standard library contains one such implicit conversion: the implicit conversion of a streams
tobool
gives!s.fail()
C#
In C#, there are the reserved keywords true
and false
. Variables to hold these values are declared as either bool
or Boolean
. These types are identical, as bool
is just shortand for Boolean
. The collection type BitArray
returns its values as Boolean
, packing 8 values into each byte (In contrast, the Boolean
type uses the entire byte for one value).
Unlike C/C++, there is no converstion in C# between other types and Boolean
.
Clean
The standard library defines a data type Bool
, which has exactly two members:
<lang clean>::Bool = False | True</lang>
In addition to all the functionality of any other Clean algebraic data type (e.g. pattern matching), and the specified derived typeclass instances, the built-in guard (“|
”) and if
syntaxes use Bool.
As with any other Clean data type, there are no automatic conversions of other types to Bool.
Clojure
The boolean constants are true and false. In a conditional context, the only false values are false and nil -- every other value is true.
Common Lisp
The only value in Common Lisp that is false is the symbol nil
; all other values are true. The symbol t
is the canonical true value.
Considered as variables, nil
and t
are bound to themselves ("self-evaluating"). nil
, as well as being false, is used as the empty list; i.e. an empty list is false.
For more information, follow the links from CLHS: Type BOOLEAN.
D
In D, there are constants true and false to represent their respective values. Implicit conversions are listed below:
- any integer type, where 0 converts to false, and any other value converts to true
- any floating point type, where again, 0 gives false and everything else gives true
- any enumeration type, again 0 gives false, anything else true
- any pointer type, where the null pointer gives false and any other pointer gives true
- any reference type, where the null reference gives false and any other reference gives true
- any user-defined type with an implicit conversion operator either to bool or to a built-in type which itself can be converted to bool
E
E defines two basic objects true
and false
, and the boolean
guard which accepts them. All builtin operations which take booleans (e.g. the if
control structure) coerce the input to boolean.
<lang e>? if (true) { "a" } else { "b" }
- value: "a"
? if (false) { "a" } else { "b" }
- value: "b"
? if (90) { "a" } else { "b" }
- problem: the int 90 doesn't coerce to a boolean</lang>
No objects in the standard library coerce to boolean, but user-written objects may choose to do so; they can then be used in place of booleans.
<lang e>? def bowlian { > to __conformTo(guard) { > if (guard == boolean) { return true } > } > } > if (bowlian) { "a" } else { "b" }
- value: "a"</lang>
Erlang
Erlang doesn't technically define boolean types. Instead, the atoms true and false are used. However, they are integrated well enough into the language there should be no problem with that as long as you don't expect false and true to mean anything but literal false and true.
<lang erlang>1> 1 < 2. true 2> 1 < 1. false 3> 0 == false. false</lang>
Factor
In Factor any value except f
is true, with t
being the canonical true value.
FALSE
Zero is false and non-zero is true. This is used by the if and while operators (? and #). Comparators (= and <) yield -1 for true and 0 for false.
Forth
In conditionals, zero is false, non-zero is true. There are predefined constants for the canonical forms. For FORTH-83 or later, FALSE is zero and TRUE is -1 (all bits set). For earlier FORTH standards, FALSE is zero and TRUE is 1. <lang forth>TRUE . \ -1 FALSE . \ 0</lang>
Fortran
Fortran has a logical data type which can be set to either .true. or .false..
Haskell
The Haskell standard Prelude defines a data type Bool
, which has exactly two members:
<lang haskell>data Bool = False | True deriving (Eq, Ord, Enum, Read, Show, Bounded)</lang>
In addition to all the functionality of any other Haskell algebraic data type (e.g. pattern matching), and the specified derived typeclass instances (e.g. False == False
, succ False == True
, (maxBound :: Bool) == True
, etc.), the built-in guard (“|
”) and if
syntaxes use Bool.
As with any other Haskell data type, there are no automatic conversions of other types to Bool.
J
False is 0, true is 1. This is an advantage.
Java
Java has true and false keywords, representing the only values of type boolean. There are also object wrappers Boolean.TRUE and Boolean.FALSE, of type Boolean which may be un-boxed into booleans (auto-unboxed in Java 1.5+). There are no automatic conversions from any other types into boolean, and it is a compile-time error to use any type other than boolean or Boolean in a place that expects a boolean (e.g. if-statement condition, while-statement condition, operand of a logical operator, etc.).
JavaScript
The Boolean type has two values: true
and false
The following table shows the result of type conversions to boolean:
- Undefined: any undefined value is converted to
false
- Null:
false
- Number: the numbers
0
,-0
,NaN
arefalse
; otherwisetrue
- String: the empty (zero-length) string is
false
; otherwisetrue
- Object: any object is converted to
true
(source: ECMAScript Language Reference)
Logo
Logo has predefined symbols for true and false ("true and "false), which are the values returned by predicates and required by logical operators and conditionals. <lang logo>print 1 < 0 ; false print 1 > 0 ; true if "true [print "yes] ; yes if not "false [print "no] ; no</lang> Unlike other lispy languages, there are no other implicit conversions. You must test explicitly for zero or empty collections. <lang logo>if equal? 0 ln 1 [print "zero] if empty? [] [print "empty] ; empty list if empty? "|| [print "empty] ; empty word</lang>
Lua
All values in Lua other than false
or nil
are considered true
:
<lang lua>
if 0 then print "0" end
if "" then print"empty string" end
if {} then print"empty table" end
if nil then print"this won't print" end
if true then print"true" end
if false then print"false" end
</lang>
Metafont
Metafont has the type boolean; a boolean variable can be true or false. Using non boolean values (or expressions that do not evaluate to a boolean value) results in a recoverable error; by default, any non-boolean value is interpreted as false.
Modula-3
Similar to Ada, Modula-3 has a built-in BOOLEAN type defined as <lang modula3>TYPE BOOLEAN = {FALSE, TRUE}</lang>
MUMPS
M[UMPS] has no data types per se, however, any value can be coerced to a specific interpretation by applying certain operators.
Internally, the language treats any "zero" value as a "false", and any "non-zero"
value as a "true".
Values like 1, 2, 13245.08763, .1, "0.00001234ABC" and "1234ABC" are "true".
Values like 0, -3, "", " 123" (note the leading space in this one),
"+++++567", "abc", "abc1245" are "false".
When a boolean operator is applied to an operand, the value of that operand is coerced to a logical value, that is: if the value starts out with a sequence of digits that look like a non-zero number, the value is "true" (1), and otherwise that value is "false" (0).
There are two standardized binary boolean operators: & (and) and ! (or). Newer implementations of the language may also support !! (exclusve or). There is one unary boolean operator: ' (not).
Objective-C
Objective-C follows pretty much the same rules as C. In addition to C, Objective-C has a BOOL
boolean type, with values YES
for true and NO
for false. Objective-C also adds several special types of pointers; for pointers to objects (values of type id
), the nil
pointer is false, everything else is true; for pointers to classes (values of type Class
), the Nil
pointer is false, everything else is true.
OCaml
OCaml defines a built-in data type bool
, which has exactly two members, represented by the keywords true
and false
:
<lang ocaml>type bool = false | true</lang>
In addition to all the functionality of any other OCaml algebraic data type (e.g. pattern matching), and the functionality of any other OCaml data type (e.g. comparisons false = false
, false < true
, etc.), bool
is also used in the guards in pattern matching (“when
”) and if
and while
syntaxes.
As with any other Ocaml data type, there are no automatic conversions of other types to bool.
Octave
Octave uses true (1) and false (0). The class of a variable holding a boolean value is logical, which however can be casted to a numeric class, so that r = true; r * 2
gives 2 as result. Any non-zero value is interpreted as true, and 0 as false.
Oz
true and false are the only boolean values. No other values are automatically converted to bool.
Pascal
In all flavors of pascal there is no such foolishness as numbers of empty strings or pointers ( initialized or otherwise ) being evaluated as boolean. There is the boolean type as defined by the RTL statements such as: <lang pascal> var
pInt : ^integer ; ValidP : boolean ;
</lang>
<lang pascal> if pInt then ... </lang>
or
<lang pascal> if pInt^ then ... </lang>
Will always be a syntax error. The following correct evaluations of variables are allowed:
<lang pascal> if not(pInt = nil) then ValidP := true ; </lang>
or
<lang pascal> if ( ValidP ) and (pInt^ <> 0) then ... </lang>
Perl
The values in Perl that are false are: 0 (as a number (including 0.0), or as the string '0', but not the string '0.0'), the empty string '', the empty list (), and undef. Everything else is true. See perlsyn.
Objects may break these rules at will via overloading.
Perl has no builtin "true" or "false" keywords. However, as a special case, literal 1s and 0s will never cause a "Useless use of a constant in void context" warning. Another special case worth pointing out here is that the string '0 but true' won't provoke a warning if it's used as a number.
Perl 6
Perl 6 provides an enumeration Bool
with two values, True
and False
. Values of enumerations can be used as ordinary values or as mixins:
<lang perl6>my Bool $crashed = False; my $val = 0 but True;</lang>
For a discussion of Boolean context (i.e. how Perl decides whether something is true or false), see Synopsis 2.
PHP
The values in PHP that are false are: FALSE, NULL, the number 0 (as an integer 0, float 0.0, or string '0', but not the string "0.0"), the empty string "", the empty array array(), and "SimpleXML objects created from empty tags"(?).
Everything else is true. The keyword TRUE exists. [2]
PicoLisp
Like in all Lisps, the symbol 'NIL' denotes "false", any other value "true".
Some functions return the symbol 'T' for "true" if no other useful (non-NIL) value is available in the given context. Note that 'NIL' and 'T' are written in uppercase letters (PicoLisp is case-sensitive).
Pike
<lang pike> > 0; (3) Result: 0 > false; (4) Result: 0 > 0; (6) Result: 0 > !true; (7) Result: 0 > true; (8) Result: 1 > 1; (9) Result: 1 > </lang>
PL/I
<lang PL/I> true is '1'b and false is '0'b </lang>
PowerBASIC
In addition to what's noted above under BASIC (above), PowerBASIC for Windows (and probably PB/CC as well) has the ISTRUE
and ISFALSE
functions. According to the help file, they "return the logical truth or falsity of a given expression". (PB lacks a boolean data type, so the usual practice is to use integers in PB/DOS and longs PB/CC and PB/Win.)
<lang powerbasic>DIM x AS LONG x = ISTRUE(1 = 1) ' returns -1 x = ISTRUE(1 = 0) ' returns 0 x = ISFALSE(1 = 1) ' returns 0 x = ISFALSE(1 = 0) ' returns -1</lang>
PowerShell
Two automatic variables exist for this purpose: <lang powershell>$true $false</lang> However, nearly everything can be converted to a boolean value, as detailed in the following list:
- any non-zero number evaluates to true, zero evaluates to false
- any non-empty string evaluates to true, an empty string evaluates to false
- an empty array evaluates to false
- an array containing exactly one item evaluates to whatever the only item evaluates to
- any array with more than one item evaluates to true
- a reference to any object evaluates to true,
$null
evaluates to false
Python
Python has a boolean data type with the only two possible values denoted by True
and False
.
The boolean type is a member of the numeric family of types, and when used in a numeric, but not boolean context, True
has the value one and False
the value zero. Conversely, when numbers are used in a boolean context, zero is False and anything other than zero is True.
In a boolean context, Python extends what is meant by true and false by accepting empty collection types, such as an empty dict or an empty list as being False, and non-empty collection types as being True, so in an if statement one might branch on a list which would be the same as testing if the list had any contents.
A user-created class that defines a .__nonzero__() method to return False, or whose .__len__() method returns 0 will be treated as False
, otherwise the class/instance is treated as True
.
None is also False
in a boolean context.
Some examples: <lang python>>>> True True >>> not True False >>> # As numbers >>> False + 0 0 >>> True + 0 1 >>> False + 0j 0j >>> True * 3.141 3.141 >>> # Numbers as booleans >>> not 0 True >>> not not 0 False >>> not 1234 False >>> bool(0.0) False >>> bool(0j) False >>> bool(1+2j) True >>> # Collections as booleans >>> bool([]) False >>> bool([None]) True >>> 'I contain something' if (None,) else 'I am empty' 'I contain something' >>> bool({}) False >>> bool("") False >>> bool("False") True</lang>
R
Similarly to Octave, R uses TRUE and FALSE, kept in variable of class logical, which is silently casted to 1 (TRUE) or 0 (FALSE) if used as numeric value. The opposite is also true: the value 0 can be used as FALSE, and non-zero numbers as TRUE.
The values T and F are given the values TRUE and FALSE respectively (for compatibility with S-Plus), though these may be changed to other values by the user.
REBOL
REBOL uses values of type logic! to represent boolean values. A boolean value can be 'true' or 'false', which also happen to be understood as predefined constants. Other constants are also provided to improve program readability:
True | False |
---|---|
true | false |
yes | no |
on | off |
any [block! series! date! number! string! ...] | none |
As the last true value implies, pretty much any other type will evaluate to true. This is important to remember if you're used to a language where the value "0" is considered to be false -- in REBOL, it's true.
Ruby
The only values in Ruby that are false are: false
and nil
. They have synonyms FALSE
and NIL
.
Everything else is true. Constants true
(and TRUE
) exist. Note for Python and Perl users: unlike Python, in Ruby, the number 0
, the empty string, the empty array, and the empty hash, etc. are all true; you can instead use the zero?
method to test for 0, and the .empty?
method to test for an empty sequence.
false
, nil
and true
are singleton instances of classes FalseClass
, NilClass
and TrueClass
respectively.
[3]
Scheme
The only value in Scheme that is false is #f.
Everything else (including the empty list, unlike Lisp) is true. The constant #t represents the canonical true value.
Seed7
Seed7 defines the type boolean. The only values of boolean are TRUE and FALSE. There are no automatic conversions from any other types into boolean, and it is a compile-time error to use any type other than boolean in a place that expects a boolean (e.g. if-statement condition, while-statement condition, operand of a logical operator, etc.).
Slate
Use True or False.
Smalltalk
Smalltalk uses the Boolean class, which has two subclasses (True and False), and true and false are instances of those classes. E.g. an expression like 5 = 5 returns true.
SNUSP
Zero is false and non-zero is true, as used by the sole skip-if-zero operator (?). <lang snusp>$!/?\=false= + =true=#
\-/</lang>
Standard ML
Standard ML defines a top-level data type bool
, which has exactly two members, true
and false
:
<lang sml>datatype bool = false | true</lang>
In addition to all the functionality of any other Standard ML algebraic data type (e.g. pattern matching, equality false = false
), bool
is also used in if
and while
syntaxes.
As with any other Standard ML data type, there are no automatic conversions of other types to bool.
Tcl
- True values
- 1 (or other non-zero number, e.g., 42), true, yes, on
- False values
- 0 (or other zero number, e.g., 0.0), false, no, off
Any of these values may be abbreviated, and mixed-case spellings are also acceptable. [4] Any other value gives an error. In an interactive tclsh session: <lang tcl>% if {""} then {puts true} else {puts false} expected boolean value but got ""</lang>
Test for the boolean value of a string can be stuff like <lang tcl>if {[string is false -strict $string]} ...</lang> which will test for "no" or "NO" or "0" or "False" or ...
TI-89 BASIC
There are boolean literals true
and false
. No other values may be used where a boolean is expected.
Visual Basic
VB has the Boolean
data type and the constants True
and False
, in addition to what's listed under BASIC, above. When used outside of a boolean context, True
and False
return values depending on their context -- -1
and 0
in a numeric context, "True"
and "False"
if used as strings.
<lang vb>Dim x As Boolean x = IIf(Int(Rnd * 2), True, False) MsgBox x</lang>
XSLT
<lang xml><xsl:if test="true() or false()">
True and false are returned by built-in XPath functions.
</xsl:if> <xsl:if test="@myAttribute='true'">
Node attributes set to "true" or "false" are just strings. Use string comparison to convert them to booleans.
</xsl:if> <xsl:if test="@myAttribute or not($nodeSet)">
Test an attribute for its presence (empty or not), or whether a node set is empty.
</xsl:if></lang>
- Programming Tasks
- Basic language learning
- Ada
- AutoHotkey
- AWK
- AppleScript
- BASIC
- Befunge
- Brainf***
- C
- C++
- C sharp
- Clean
- Clojure
- Common Lisp
- D
- E
- Erlang
- Factor
- FALSE
- Forth
- Fortran
- Haskell
- J
- Java
- JavaScript
- Logo
- Lua
- Metafont
- Modula-3
- MUMPS
- Objective-C
- OCaml
- Octave
- Oz
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- Pike
- PL/I
- PowerBASIC
- PowerShell
- Python
- R
- REBOL
- Ruby
- Scheme
- Seed7
- Slate
- Smalltalk
- SNUSP
- Standard ML
- Tcl
- TI-89 BASIC
- Visual Basic
- XSLT