Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

Views expressed in these public forums are not endorsed by Drexel University or The Math Forum.


Math Forum » Discussions » Software » comp.soft-sys.math.mathematica

Topic: Applying "Replace" to subsets of lists
Replies: 2   Last Post: Dec 20, 2012 3:19 AM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Bob Hanlon

Posts: 906
Registered: 10/29/11
Re: Applying "Replace" to subsets of lists
Posted: Dec 20, 2012 3:19 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

magicFunction[list_List, part_, rule_Rule] :=
ReplacePart[list, part -> (list[[part]] /. rule)]

magicFunction[{{b, 2}, b}, 2, b -> 1]

{{b, 2}, 1}

magicFunction[{{b, 2}, b^2}, 2, b -> 1]

{{b, 2}, 1}

magicFunction[{{b, 2}, b^2}, 1, b -> 1]

{{1, 2}, b^2}


Bob Hanlon


On Wed, Dec 19, 2012 at 4:55 AM, <abed.alnaif@gmail.com> wrote:
> Hello,
> Say I have the following list, and I'd like to replace the second 'b' with the value 1, leaving the first b untouched:
>
> MagicFunction[{{b, 2}, b}] = {{b, 2}, 1}
>
> How do I do this? I've tried the following:
>
> This doesn't work since it replaces both 'b'
> In: {{b, 2}, b} /. b -> 1
> Out: {{1, 2}, 1}
>
> This doesn't work (I'm not sure why):
> In: {{b, 2}, b} /. {{x_, y_}, f_[b]} -> {{x, y}, 1, f[1]}
> Out: {{b, 2}, b}
>
> This works:
> In: {{b, 2}, b} /. {{x_, y_}, b} -> {{x, y}, 1}
> Out: {{b, 2}, 1}
>
> However, 'b' may appear in different forms, in which case the previous approach fails:
> In: {{b, 2}, b^2} /. {{x_, y_}, b} -> {{x, y}, 1}
> Out: {{b, 2}, b^2}
>
> Using the 'levelspec' argument of 'Replace' also fails since 'b' can appear in different forms:
> In: Replace[{{b, 2}, b^2}, b -> 1, 1]
> Out: {{b, 2}, b^2}
> In: Replace[{{b, 2}, b^2}, b -> 1, 2]
> Out: {{1, 2}, 1}
>
> Thank you,
>
> Abed
>





Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.