4

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.

iav
  • 2,006
  • 17
  • 26
  • 1
    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) – Mr.Wizard Oct 07 '14 at 20:00

1 Answers1

8

Just add the parentheses

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

AssociationQ@as
(* True *)

Rule (->) has lower precedence then &.

ybeltukov
  • 43,673
  • 5
  • 108
  • 212