4
$\begingroup$

I've encountered confusing behavior of Association when I try to use it for storing pure functions.

For example:

as = <|"1" -> # + 1 &|>

Association["1" -> #1 + 1 &]

Strangely:

AssociationQ@as

False

and it is not possible to extract the value by the key:

as["1"]

Association["1" -> #1 + 1 &]["1"]

Is this the intended behavior?

P.S. Wrapping pure functions in Hold[] solves the problem, but I'm still curious why doesn't Association work without it.

$\endgroup$
1
  • 1
    $\begingroup$ I have closed this as a duplicate as the origin of the unexpected behavior is the same: the grouping of the & operator. Please also see: (30425) $\endgroup$
    – Mr.Wizard
    Commented Oct 7, 2014 at 20:00

1 Answer 1

8
$\begingroup$

Just add the parentheses

as = <|"1" -> (# + 1 &)|>
(* <|"1" -> (#1 + 1 &)|> *)

AssociationQ@as
(* True *)

Rule (->) has lower precedence then &.

$\endgroup$

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