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} -- trueYou 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} -- trueLists 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} -- falseSince 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}} -- trueThe 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"} ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access