Containment Operators
Containment may apply to two
strings, two lists, or two records. The
result is a boolean. Containment implies comparison, and the nature
of comparisons involving strings can be influenced by a
considering
clause; see Chapter 12.
The fact that in the case of list containment both operands must be lists is a little counterintuitive at first. Thus:
{1, 2} contains {2} -- true
You might have expected to say:
{1, 2} contains 2 -- true
You can say that,
but only because 2
is coerced to
{2}
implicitly. In other words, the second operand
is not an element; it’s a
sublist. Thus you can ask about more than one
element at once. For example:
{1, 2, 3} contains {2, 3} -- true
Lists are ordered, so the items of the sublist you ask about must appear consecutively and in the same order in the target list; these are false:
{1, 2, 3} contains {1, 3} -- false {1, 2, 3} contains {3, 2} -- false
Since lists can contain lists, you may have to use an explicit extra level to say what you mean:
{{1}, {2}} contains {2} -- false {{1}, {2}} contains {{2}} -- true
The first is false because 2
is not an element of
the first list, and {2}
is not going to be coerced
to {{2}}
for you—it’s a
list already so there’s nothing to coerce.
In the case of record containment, both the label and the value must match for containment to be true. So:
{name:"Matt", age:"49"} contains {name:"Matt"} -- true {name:"Matt", age:"49"} contains {title:"Matt"} -- false {name:"Matt", age:"49"} contains {name:"Socrates"} ...
Get AppleScript: The Definitive Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.