Skip to content

Cases ​

The elements of a collection matching a pattern.

✓ checked against that system · ! checked, with disagreements (hover a chip)FungrimCasesWolfram LanguageCases✓
Cases(collection, pattern)every element of collectioncollection that matches patternpattern, in order.
Typed signatures
TypePackageApplies
(collection<any>, any) -> collectioncombinatoricsalways

Domain: Collections

Details
  • Matches compute-engine's own wildcards: a bare _ (or named, _a) matches any single element, __/___ match one-or-more/zero-or-more within a structural pattern, and a pattern built from a head applied to wildcards (e.g. List(_a)List(\_a)) matches that structure.
  • A plain value (no wildcard) matches by exact equality, same as Count.
  • Only the top level of the collection is searched.

Examples

Basic #
live ↗
InCases([1,a,2,b],_⁡)\mathrm{Cases}(\bigl\lbrack1, a, 2, b\bigr\rbrack, \operatorname{\_})Out[1,a,2,b]\bigl\lbrack1, a, 2, b\bigr\rbrack
Scope #

A plain value keeps only the elements equal to it

live ↗
InCases([1,2,1,3,1],1)\mathrm{Cases}(\bigl\lbrack1, 2, 1, 3, 1\bigr\rbrack, 1)Out[1,1,1]\bigl\lbrack1, 1, 1\bigr\rbrack

A structural pattern keeps elements shaped like it

live ↗
InCases([[1],2,[3]],[_a⁡])\mathrm{Cases}(\bigl\lbrack\bigl\lbrack1\bigr\rbrack, 2, \bigl\lbrack3\bigr\rbrack\bigr\rbrack, \bigl\lbrack\operatorname{\_a}\bigr\rbrack)Out[[1],[3]]\bigl\lbrack\bigl\lbrack1\bigr\rbrack, \bigl\lbrack3\bigr\rbrack\bigr\rbrack
Properties #

For a plain value, Cases and Count agree on how many

live ↗
InLength(Cases([1,2,1,3,1],1))=Count([1,2,1,3,1],1)\mathrm{Length}(\mathrm{Cases}(\bigl\lbrack1, 2, 1, 3, 1\bigr\rbrack, 1))=\mathrm{Count}(\bigl\lbrack1, 2, 1, 3, 1\bigr\rbrack, 1)OutTrue\mathrm{True}
Possible issues #

compute-engine's wildcards carry no type: _Integer is just a named wildcard, so it matches every element

live ↗
InLength(Cases([1,a,2,b],_Integer⁡))\mathrm{Length}(\mathrm{Cases}(\bigl\lbrack1, a, 2, b\bigr\rbrack, \operatorname{\_Integer}))Out44

Wolfram's _Integer pattern only matches integers, here 2 (1 and 2).

About
Examples5
Checked againstWolfram Language 2 agree1 unevaluated
CrosswalkFungrimWolfram Language

See also: Count, Select