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$

closed as off-topic by m_goldberg, C. E., ciao, Michael E2, LouisB Oct 17 at 4:20

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – m_goldberg, C. E., ciao, Michael E2, LouisB
If this question can be reworded to fit the rules in the help center, please edit the question.

  • $\begingroup$ You can also write fas["fa"]. $\endgroup$ – Szabolcs Oct 10 at 8:20
  • $\begingroup$ If you want to use Part, you must write fas[[2]], $\endgroup$ – m_goldberg Oct 10 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 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 at 15:52

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