Group Abstract Group Abstract

Message Boards Message Boards

0
|
11K 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 7 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

I'm still not clear on exactly what you want but look at Reap and Sow (or related, Throw and Catch). You can use them in a "myWhen" function that triggers your action. Note that you can use the optional extra argument to Reap and Sow to gather up different results in different lists.

I hope this helps.

Regards,

Neil

POSTED BY: Neil Singer

Thank you for your response Neil, however this isn't what I'm looking for. I'm in need of something that will either look for trueness in the left hand side of the > or a structure match and then evaluate the right hand side of the > that way I can do conditional tasks that partially relate. Again, thank you for taking your time to respond!

POSTED BY: Joshua Champion

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
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard