Group Abstract Group Abstract

Message Boards Message Boards

0
|
9.3K Views
|
5 Replies
|
4 Total Likes
View groups...
Share
Share this post:

Does there exist a Rule that performs instead of being a replacement rule?

Posted 6 years ago
POSTED BY: Joshua Champion
5 Replies

Mathematica is an expression rewriting language. Rules and definitions basically say "See this? Rewrite as that.". And then, once it has done the rewrite, it re-evaluates the resulting expression. So, what you want doesn't seem to be anything special. If (shudder), you want the rewritten expression to have side effects, you can arrange it.

Perhaps what you're looking for is RuleDelayed.

POSTED BY: John Doty

Mutating a List is generally a difficult and inefficient way to get things done in Mathematica. I think it's much easier to define a function that yields rewritten list elements as needed, and use the magic Nothing to excise unwanted results. First the case we want:

f[x_Integer] := x^2

Now, a catch-all for the cases we don't want:

f[_] := Nothing

Then, just Map f to your input:

Map[f, {1, 2, 3, Pi, E, 5}]
(*
  {1, 4, 9, 25}
*)
POSTED BY: John Doty
POSTED BY: Neil Singer

Joshua,

I think you want Cases. Modifying their first documentation example a bit:

In[2]:= Cases[{1, 1, f[a], 2, 3, y, f[8], 9, f[10]}, i_Integer -> i^2]

Out[2]= {1, 1, 4, 9, 81}

Regards,

Neil

POSTED BY: Neil Singer
POSTED BY: Joshua Champion
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard