6
$\begingroup$

I just started learning Mathematica. I was wondering if it is possible to use a function as an value in an association. Ideally, it would be something like this:

fas = Association["a" -> 2/5, "fa" -> (# + 1/2) &];

And I wish that I could use fas[["fa"]] to get access the function (# + 1/2) &.

$\endgroup$
  • $\begingroup$ You can also write fas["fa"]. $\endgroup$ – Szabolcs Oct 10 '19 at 8:20
  • $\begingroup$ If you want to use Part, you must write fas[[2]], $\endgroup$ – m_goldberg Oct 10 '19 at 13:48
  • $\begingroup$ It's a question of precedence. Try "fa" -> (# + 1/2 &) with the parentheses around the function, including the &. $\endgroup$ – Michael E2 Oct 14 '19 at 18:19
11
$\begingroup$

This is a precedence issue.

"fa" -> (# + 1/2) & is interpreted as ( "fa" -> (# + 1/2) ) &.

Write "fa" -> ( (# + 1/2) & ) instead.

$\endgroup$
  • $\begingroup$ Thanks a lot! That works! $\endgroup$ – dushoda Oct 10 '19 at 15:52

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