Message Boards Message Boards

1
|
6296 Views
|
3 Replies
|
4 Total Likes
View groups...
Share
Share this post:

Transforming list elements using Cases[ ]

Posted 9 years ago

Re Mathematica 10.3 under Windows 7.

From the list {1,2,3,4,5} I want to zero in on 1 and 3 and return the list of their squares, i.e., {1,9}.

This is easy enough to do using

Cases[Range@5,1|3]^2.  

Noting that this example is a grossly oversimplified instance of something else, I want to do this using a form like

Cases[Range@5, (1|3) :> #^2&] 

(this returns an empty list). Can this be done? I've looked at the documentation PatternOverview and don't find an answer (although may have missed it).

Thanks.

POSTED BY: Bruce Colletti
3 Replies

The correct way of using Cases would be:

Cases[Range@5, (x : (1 | 3)) :> x^2]

Cases doesn't accept pure function like that. Better is to assign it some "named blank" and then transform that.

POSTED BY: Sander Huisman
Posted 9 years ago

Bingo! Exactly what I sought. Nassir's earlier reply was also instructive. Thanks to you both, Nassir and Sander.

POSTED BY: Bruce Colletti

If you want to map a function to list, then

(#^2) & /@ Cases[Range[5], (1 | 3)] 

gives

{1, 9}
POSTED BY: Nasser M. Abbasi
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract