Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing commas in list with arrow ->

How do I replace the commas on the second level of a list with replacement arrows?

For example, this:

{{a, girl}, {b, girl}, {c, girl}, {e, girl}, {g, girl}}

To this:

{{a->girl}, {b->girl}, {c->girl}, {e->girl}, {g->girl}}

Replace doesn't work because it thinks the comma shouldn't be there. Putting it in quotes doesn't work, nor does StringReplace

What I think it should be:

Replace[list, "," -> "->", {2}]
like image 216
Alec Avatar asked Dec 23 '10 01:12

Alec


3 Answers

The following gives the desired result:

lop = {{a, girl}, {b, girl}, {c, girl}, {e, girl}, {g, girl}} (* list o' pairs *)

{#1 -> #2}& @@@ lop

To me that's the most natural way to do it. Here's another way that avoids the use of a lambda function:

List /@ Rule @@@ lop

More on that way of using @@@: In Mathematica, what does @@@ mean?

If you don't like @@@ you can do this:

{First@# -> Last@#}& /@ lop

And here's yet another way, using a replacement rule:

lop /. {x_,y_}->{x->y}

And, what the heck, here's the least intuitive way I can think of to do it:

Transpose@{Thread[Rule@@Transpose[lop]]}

(Note that /. is shorthand for ReplaceAll, /@ is shorthand for Map, @@ is shorthand for Apply, and f@x is just another way to write f[x].)

like image 99
dreeves Avatar answered Nov 03 '22 01:11

dreeves


{{a, girl}, {b, girl}, {c, girl}, {e, girl}, {g, girl}}/.{x_, y_} -> {Rule[x,y]} 

Result:

{{a -> girl}, {b -> girl}, {c -> girl}, {e -> girl}, {g -> girl}}  

These things are explained under the tutorials for patterns and transformation rules in the help system.

HTH!

Edit

You CAN do it by using Strings ... but it is not the right way:

x = ToString[{{a, girl}, {b, girl}, {c, girl}, {e, girl}, {g, girl}}];
y = StringReplace[x, "{" ~~ d_ ~~ ", " ~~ Shortest[f__] ~~ "}" -> 
                     "{" ~~ d ~~ "->" ~~ f ~~ "}"];
z = ToExpression@y

Edit 2

The List[] and the Sequence[] are two constructs that you must understand to start working with Mathematica.

Replacing the braces or the comma in a List is not possible, because List[] is a function and the {..,..,..,..} is just notation.

Try the following to understand it:

 {{a,b},{c,d}} //FullForm  

and

{a, b} /. List -> Plus
like image 22
Dr. belisarius Avatar answered Nov 02 '22 23:11

Dr. belisarius


MapApply works nicely here:

In[1]:= Rule @@@ {{a, girl}, {b, girl}, {c, girl}, {e, girl}, {g, girl}}

Out[1]= {a -> girl, b -> girl, c -> girl, e -> girl, g -> girl}
like image 37
Joshua Martell Avatar answered Nov 03 '22 01:11

Joshua Martell