7
$\begingroup$

Consider an association which contains a key which must not be prematurely evaluated.

assoc = <| key :> value |>

For example, a value of a[[b]] would throw a Part error until symbols a and b are substituted.

We might wish to obtain this value in its unevaluated form, e.g. to display. Simply calling

assoc[key]

will evaluate value (and in that example, throw a Part error).

One trick is to exploit that matched patterns are unevaluated:

assoc /. KeyValuePattern[ key :> v_ ] -> Hold[v]

but this seems needlessly hacky for what must be a common operation. What's the right way to obtain Hold[value]?

$\endgroup$

2 Answers 2

9
$\begingroup$

Ironically, the probably simplest answer is literally Extract, just as in the question's title:

Extract[assoc, {Key[key]}, Hold]

(* Hold[value] *)
$\endgroup$
8
$\begingroup$

There is a Lookup variant that supports wrapping with a head before evaluation:

Lookup[assoc, key, Missing[], Hold]
$\endgroup$
1
  • 1
    $\begingroup$ Note this requires v12.1 (incompatible with my 11.1) $\endgroup$
    – Anti Earth
    Commented May 9, 2021 at 16:34

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.