TIP #182 Version 1.8: Add [expr bool] Math Function

This is not necessarily the current version of this TIP.


TIP:182
Title:Add [expr bool] Math Function
Version:$Revision: 1.8 $
Author:Joe Mistachkin <joe at mistachkin dot com>
State:Draft
Type:Project
Tcl-Version:8.5
Vote:Pending
Created:Tuesday, 23 March 2004

Abstract

This TIP proposes a new function bool() for use with the expr command.

Rationale

This TIP proposes a new function, bool(), that does casting to boolean much as int(), double() and wide() cast to their respective types. This is firstly for reasons of symmetry between the types, secondly because it allows for clearer expression of what is happening than the alternative (based on the conditional operator), and thirdly because it may also allow for conversion of values that are not strictly boolean under any interpretation, and so make certain kinds of user interface more robust. For example:

# See if they want to enable an option...
puts stdout "Do you want to enable option X?"
# Read their response.
gets stdin response
# Convert "yes/no", "true/false", "on/off" to 1/0.
set Options(X) [expr {bool($response)}]

# ... Write the options to a file ...
set configFile [open "config.file" "w"]
puts $configFile "array set \{[array get Options]\}"
close $configFile

What about the string is true and string is false commands? Those commands are suitable for determining if an arbitrary string could possibly be converted to a boolean, however, they do not, in fact, perform such a conversion, nor do they raise errors if the string cannot be converted (like int() does and bool() will do). In addition, using the results of the string is commands inside of a large expr expression could become quite cumbersome.

Proposed Change

A new math function named bool would be added to the list of functions supported by the expr command.

expr bool( value )

This would return "1" for any value of value that is non-zero (plus all non-numeric strings accepted as true by Tcl_GetBoolean()) and "0" otherwise. If the value cannot be converted to a boolean, an error is raised.

Internally, the function should use something semantically equivalent to using Tcl_GetBoolean().

Reference Implementation

A reference implementation of this TIP is availble [1].

Copyright

This document has been placed in the public domain.


Powered by TclThis is not necessarily the current version of this TIP.

TIP AutoGenerator - written by Donal K. Fellows