Artifact [16a573d0aa]

Login

Artifact 16a573d0aa358109c6a18bb8948474847dda54d6a60aec9e0dfdf00247a4bed4:


TIP:            201
Title:          Add 'in' Operator to [expr]
Version:        $Revision: 1.5 $
Author:         Jeff Hobbs <[email protected]>
State:          Final
Type:           Project
Vote:           Done
Created:        21-May-2004
Post-History:   
Keywords:       Tk,list membership,sets
Tcl-Version:    8.5

~ Abstract

This TIP proposes new '''expr''' operators "'''in'''" and "'''ni'''" that simplifies the standard "does this item exist in list" '''lsearch''' case in expressions, with "'''ni'''" being "not in".

~ Rationale

The addition of '''in''' and '''ni''' operators is syntactic sugar for the
verbose '''lsearch''' operation that checks for a single items
existence (or non-existence) in a list.  It serves to simplify the reading and writing of
code that requires this comparatively-common operation.  The
operators will do '''lsearch -exact''' searching as well, which would
correct an inadvertant bug that many users introduce into their code
when they write:

| if {[lsearch $list $item] != -1} { ... }

as '''lsearch''' does '''-glob''' matching by default.  I have found
this error repeated often in user code.

Note that [133] uses an '''in''' operator as a motivating case, but is
actually proposing a much more general alteration.

~ Specification

A new infix '''expr''' operators '''in''' and '''ni''' will be added, making the
following pairs of commands equivalent (assuming nobody has redefined
'''lsearch''' of course):

 * Searching for an arbitrary item in an arbitrary list.

| if {[lsearch -exact $list $item] != -1} { ... }
| if {$item in $list} { ... }

 * Checking for the absence of an arbitrary item from an arbitrary
   list.

| if {[lsearch -exact $list $item] == -1} { ... }
| if {$item ni $list} { ... }

~ Comments

There was a proposal to add a separate operator "'''!in'''" to do
negated membership testing, but that significantly complicates the
expression parser and is likely to be harder to teach to newcomers to
Tcl, since it looks like the application of an operator to another
operator.

'''notin''' and '''ni''' were also suggested, and '''ni''' was accepted as a reasonable pair for "not in", similar to '''ne''' being "not equal".  There was some concern about '''ni''' in that TeX has a different interpretation, but that is unlikely to confuse the majority of Tcl users.

~ Reference Implementation

''[[To Follow]]''

~ Copyright

This document has been placed in the public domain.