5
$\begingroup$

The syntactic sugar for alternatives in replacement rules is clean:

{a|b|c-> 1, d->2}

Are there any analogous shorthands for keys in associations. I want to specify multiple equivalent keys in an association, like this:

<| Key[a|b|c]-> 1, Key[d]->2|>

The motivation is that sometimes the values in key-value pairs are large (and so you'd rather not flatten it out and add duplicate them for each key alias).

$ChordFormulas = <|"Major"|"Maj"->{0,4,7}, "m"|"Minor"|"Min" -> {0,3,7}, "9"|"79"->...|>

Related:

$\endgroup$
1
  • $\begingroup$ How do you want to use these associations? Are they constants or do you update (change) them frequently? If they are constants, Dispatch (or just a rule list) would work very well, I think. $\endgroup$
    – Szabolcs
    Commented Jan 19, 2016 at 9:01

1 Answer 1

1
$\begingroup$

It seems you have already done it with Alternative.

c = <|"Major" | "Maj" -> {0, 4, 7}, "Minor" | "Min" -> {0, 3, 7}|>;

You would just need KeySelect and MatchQ.

KeySelect[MatchQ[#]@"Major" &]@c
(* <|"Major" | "Maj" -> {0, 4, 7}|> *)

or with ReplaceAll.

KeySelect["Maj" /. # -> True &]@c
(* <|"Major" | "Maj" -> {0, 4, 7}|> *)
$\endgroup$
4
  • $\begingroup$ In[211]:= <|"Major" | "Maj" -> {0, 4, 7}|>["Major"] Out[211]= Missing["KeyAbsent", "Major"] $\endgroup$
    – M.R.
    Commented Jan 19, 2016 at 1:45
  • $\begingroup$ With this approach, everytime I do a query I'll need to use MatchQ which is slow. $\endgroup$
    – M.R.
    Commented Jan 19, 2016 at 1:47
  • $\begingroup$ @M.R. Only way I can think of at the moment. It does allow you to use Alternatives and store the value once like you asked. $\endgroup$
    – Edmund
    Commented Jan 19, 2016 at 1:48
  • $\begingroup$ @M.R. You can use ReplaceAll instead of MatchQ. "Maj" /. # -> True &. However, that will fall down if you ever use True as a key. $\endgroup$
    – Edmund
    Commented Jan 19, 2016 at 1:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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