MathGroup Archive 2001

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

Search the Archive

RE Map

  • To: mathgroup at smc.vnet.net
  • Subject: [mg29727] RE [mg29684] Map
  • From: Ranko Bojanic <bojanic at math.ohio-state.edu>
  • Date: Wed, 4 Jul 2001 18:43:44 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com



Benedetto Bongiorno wanted to convert the list
     a={{1, 5, 10},{25, 0, 2000},{55, 5, 2001}
into the list
      {{01, 05,10},{25, 00, 2000},{55, 05, 2001}
His program

Map[If[#<10,(StringJoin[ToString[0],ToString[#]]),#]&,a]

did not work but, as several readers pointed out, this could be 
easily corrected by adding the correct level specification:

Map[If[#<10,(StringJoin[ToString[0],ToString[#]]),#]&,a,{2}]
{{01,05,10},{25,00,2000},{55,05,2001}}

One potential problem I see here is that the result is a list of
strings and integers

Map[Head, %,{2}]
{{String,String,Integer},{Integer,String,Integer},{Integer,String,Integer}}

This can be also easily corrected by writing:

Map[If[#<10,(StringJoin[ToString[0],ToString[#]]),ToString[#]]&,a,{2}]

The main reason I am writing this letter is that Map with level
specifications does not seem to work in a slightly more complicated cases,
for instance when

  b={{1, 5, 10},{25, 0, {1,2,3,4}},{55, 5, 2001}

If we try to apply a function g to levels 2 and 3 we get
 
 ClearAll[g]
 Map[g,b,{2,3}]
 {{g[1],g[5],g[10]},{g[25],g[0],g[{g[1],g[2],g[3],g[4]}]},{g[55],g[5],g[2001]}}
 
 but this is clearly not what we wanted because of the term
 g[{g[1],g[2],g[3],g[4]}]}
  
 The only way to obtain the correct result in this case is to make g listable:
 
 SetAttributes[g,Listable]
 g[b]
{{g[1],g[5],g[10]},{g[25],g[0],{g[1],g[2],g[3],g[4]}},{g[55],g[5],g[2001]}}

This suggests the following approach to Bongiorno's problem. Define

f[x_] :=If[x<10,(StringJoin[ToString[0],ToString[x]]),ToString[x]];

and make it Listable
 
SetAttributes[f,Listable]

We obtain then

 f[a]
{{01 ,05, 10},{25, 00, 2000},{55, 05, 2001}}
f[b]
{{01,05,10},{25,00,{01,02,03,04}},{55,05,2001}}

Ranko 




  • Prev by Date: Drawing a Washer, Polar Plot Question
  • Next by Date: Re: Swiftest code to turn list of ordered pairs into Markov matrix
  • Previous by thread: Re:Drawing a Washer, Polar Plot Question
  • Next by thread: Re: Swiftest code to turn list of ordered pairs into Markov matrix [using Sequence]