1
$\begingroup$

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?

$\endgroup$
  • 2
    $\begingroup$ This should do: :>, right? $\endgroup$ – Kuba Mar 19 at 17:15
  • $\begingroup$ Or even IntegerName /@ ind. $\endgroup$ – High Performance Mark Mar 19 at 17:25
2
$\begingroup$

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} *)
$\endgroup$
  • $\begingroup$ Now I feel suitably embarrassed... $\endgroup$ – bill s Mar 19 at 17:31
  • $\begingroup$ @bill Thank you, I was feeling lonely as a high-"reputation" user posting trivial questions. :^) $\endgroup$ – Mr.Wizard Mar 19 at 18:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.