1

I have a fairly complicated expression with nested lists and I want to substitute a given string for each integer. Here's a simple example where ind is my integer-valued data structure and names is the list of strings.

ind = RandomInteger[{1, 5}, {3, 4, 5}];
names = {"one", "two", "three", "four", "five"};
ind /. {n_Integer -> names[[n]]}

This returns two things: first, a list with the integers substituted by their string names (that's good) and an error (that's bad). The error is:

Part: The expression n cannot be used as a part specification.

though of course it has been used correctly as a part spec. The question: is it really incorrect to be using a list (and an index to the list) in the replacement rule? Is there a better way of doing this?

bill s
  • 68,936
  • 4
  • 101
  • 191

1 Answers1

2

bill, this one always trips me up too. This does what you want, @Kuba beat me to it.

ind /. {n_Integer :> names[[n]]}

The way I remember the difference between :> and -> is from the examples in the MMA help.

{x, x, x} /. x -> RandomReal[]
(* {0.430466, 0.430466, 0.430466} *)

{x, x, x} /. x :> RandomReal[]
(* {0.378563, 0.0598703, 0.504099} *)
MikeY
  • 7,153
  • 18
  • 27