4
$\begingroup$

I am using conditional statements in a list of rules to replace values in a vector of data. Since the same operation can be performed faster using Lookup on associations I would like to use this alternative procedure. However, I can not figure out how incorporate a conditional statement in an association but always receive output in the form of Missing["KeyAbsent", data]. Any tips how to achieve this?

Here is some example code and corresponding output:

(*Setting up the list of rules and corresponding association*)
assoc = <|1. -> "a", 2. -> "b", x_ /; x >= 3. -> "c"|>;
rule = {1. -> "a", 2. -> "b", x_ /; x >= 3. -> "c"};

(*Apply association and rule on data*)
data = {1., 3., 2., 4.};
dataRule = data /. rule
dataAssoc = Lookup[assoc, data]

Out[1]= {"a", 3., "b", "c"}
Out[2]= {"a", Missing["KeyAbsent", 3.], "b", Missing["KeyAbsent", 4.]}

I have consulted the documentation and searched the web about my issue but have not found an answer. Apologies should I have overlooked relevant information.

Every help is dearly appreciated!

$\endgroup$
6
$\begingroup$

There is a misunderstanding here. Associations are not replacement rules. Keys are never interpreted as patterns. Associations are just a dictionary-like data structure that associates static values to static keys. The pattern in your association is treated like any other expression and is not used as a pattern, not even if you use this association with ReplaceAll.

If you are looking to speed up replacement rules, look at using Dispatch with Replace[..., {1}], not Association with Lookup.

In your particular application, you may find the default value of Lookup (3rd argument) useful.

$\endgroup$
1
  • $\begingroup$ Thank you for your reply. $\endgroup$
    – Joe W.
    Feb 11 '20 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.