Boolean values: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
(added J)
Line 84: Line 84:


As with any other Haskell data type, there are no automatic conversions of other types to Bool.
As with any other Haskell data type, there are no automatic conversions of other types to Bool.

=={{header|J}}==

False is <tt>0</tt>, true is <tt>1</tt>. This is an [http://keiapl.info/anec/#Maple advantage].


=={{header|Java}}==
=={{header|Java}}==

Revision as of 02:13, 13 July 2009

Task
Boolean values
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

Works with: gawk

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]

BASIC

Works with: QuickBasic version 4.5

QuickBasic has no keywords for true and false. Boolean expressions evaluate to 0 when false, and a non-zero value when true. Numbers also work in place of boolean expressions following those rules.

C

In C, a value which is equal to 0 is false, while a value which is not equal to 0 is 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>), where true gives true and false 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 to bool (i.e. any of the above). The C++ standard library contains one such implicit conversion: the implicit conversion of a stream s to bool gives !s.fail()

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.

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" }

  1. value: "a"

? if (false) { "a" } else { "b" }

  1. value: "b"

? if (90) { "a" } else { "b" }

  1. 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" }

  1. value: "a"</lang>

Forth

In conditionals, zero is false, non-zero is true. There are predefined constants for the canonical forms (all bits set/clear). <lang forth> TRUE . \ -1 FALSE . \ 0 </lang>

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.).

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>

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.

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.

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.

Perl has no special "true" or "false" keywords. [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. [3]

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. So, it is true even the opposite: the value 0 can be used as FALSE, and non-zero numbers as TRUE.

Ruby

The only values in Ruby that are false are: false and nil. They have synonyms FALSE and NIL.

Everything else (including the number 0 and the empty string) is true. Constants true (and TRUE) exist.

false, nil and true are singleton instances of classes FalseClass, NilClass and TrueClass respectively. [4]

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.

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.

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, true, yes, on
False values: 0, false, no, off

Any of these values may be abbreviated, and upper-case spellings are also acceptable. [5]

Any other value gives an error. In an interactive tclsh session:

% if {""} then {puts true} else {puts false}
expected boolean value but got ""

Test for the boolean value of a string can be stuff like

 if {[string is false $string]} ...

which will test for "no" or "NO" or "0" or "False" or ...