alltom.com,
Archive,
Currently Reading,
Have Read,
Micro.blog
Subscribe with RSS or @tom@micro.alltom.com
I’m working on what feels like my lispiest Mathematica project. One of the pieces I wanted was to be able to search a list of associations by pattern, like:
findAll[db, {"id" -> 42}]
should return the full record, like {<|"id" → 42, "value" -> "A"|>}
findAll[db, {"id" -> id_, "value" -> "A"} :> id]
should return all the IDs of records whose value is “A”, like {42, 99, 67}
.It turns out to be pretty simple to make a little API like that because pattern-matching is common in Mathematica so all the necessary pieces are right there, waiting to be assembled:
(* Plain search *)
findAll[o_, {pattern__}] :=
Cases[o, <|OrderlessPatternSequence[PatternSequence[pattern], ___]|>];
(* Search and map *)
findAll[o_, {pattern__} :> replacement_] :=
Cases[o, <|
OrderlessPatternSequence[PatternSequence[pattern], ___]|> :>
replacement];