MathGroup Archive 2011

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Replace

  • To: mathgroup at smc.vnet.net
  • Subject: [mg121078] Re: Replace
  • From: "Oleksandr Rasputinov" <oleksandr_rasputinov at hmamail.com>
  • Date: Fri, 26 Aug 2011 05:24:37 -0400 (EDT)
  • Delivered-to: l-mathgroup@mail-archive0.wolfram.com
  • References: <j35am1$og8$1@smc.vnet.net>

On Thu, 25 Aug 2011 12:12:01 +0100, Sam Korn <sam at kornfamily.com> wrote:

> Hi, another stupid question. I have a list, and each element in the list  
> is
> a sublist with a pair of integers. How do I replace each element along  
> the
> lines of "{5,6}" with "(5|6)"?
>
> I know it's a stupid question, and there's probably something really  
> obvious
> I'm missing, but I'm really new to Mathematica.
>
> Thanks!
> -Sam

In[1] :=
list = RandomInteger[{-5, 5}, {10, 2}]

Out[1] =
{{-4, -4}, {-1, -3}, {4, 4}, {0, -4}, {-5, 3}, {-5, 4}, {-1, -2}, {5, -2},  
{1, -1}, {-4, 1}}

In[2] :=
list /. {x_, y_} :> (x | y)

Out[2] =
{-4 | -4, -1 | -3, 4 | 4, 0 | -4, -5 | 3, -5 | 4, -1 | -2, 5 | -2, 1 | -1,  
-4 | 1}

("/." is a sigil used in infix notation to denote the function ReplaceAll.  
":>" is RuleDelayed in the same sense.)

It's unclear to me if the above is what you intended; (x | y) is  
understood by Mathematica as a pattern which matches either x or y. If you  
had wanted something that simply displays as such without having any  
particular meaning you may instead use

In[3] :=
list /. {x_, y_} :> StringForm["(`1`|`2`)", x, y]

Out[3] =
{(-4|-4),(-1|-3),(4|4),(0|-4),(-5|3),(-5|4),(-1|-2),(5|-2),(1|-1),(-4|1)}

or perhaps

In[4] :=
Format@customizedElement[x_, y_] := StringForm["(`1`|`2`)", x, y];
customizedElement @@@ list

Out[4] =
{(-4|-4),(-1|-3),(4|4),(0|-4),(-5|3),(-5|4),(-1|-2),(5|-2),(1|-1),(-4|1)}

which has the advantage of allowing other operations to be defined on  
customizedElement if desired.




  • Prev by Date: Re: Incompletely simplified Square root.
  • Next by Date: Re: FindRoot repeatedly evaluating function
  • Previous by thread: Re: Replace
  • Next by thread: Re: Replace