8
$\begingroup$

Is there a function in mathematica that allows you to generate repeated elements inline within a list. For example, let's say you provided this as input text:

{1, 2, 3, 4, Repeat[5,3], 6, 7}

Then I would want Mathematica to provide the output as

{1, 2, 3, 4, 5, 5, 5, 6, 7}

I know there already exists something similar ConstantArray and Nest but they cannot be used in the manner described above, for doing so leads to a nested list:

{1, 2, 3, 4, ConstantArray[5, 3], 6}

{1, 2, 3, 4, {5, 5, 5}, 6}

which I would then have to Flatten, a clunky solution that is less elegant than ideal.

Since I am reasonably sure that no native function exists, how would you go about building one?

$\endgroup$

closed as off-topic by ciao, Oleksandr R., m_goldberg, J. M. is away Sep 1 '15 at 1:12

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – ciao, Oleksandr R., m_goldberg, J. M. is away
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    $\begingroup$ You are looking for Sequence! Alternatively, if you really want to build it yourself, Replace with a suitable pattern will do the job. $\endgroup$ – Oleksandr R. Sep 1 '15 at 0:28
  • $\begingroup$ Sequence@ConstantArray... $\endgroup$ – ciao Sep 1 '15 at 0:28
  • 1
    $\begingroup$ @ciao Sequence@@ConstantArray[..] -- you have a typo. $\endgroup$ – Oleksandr R. Sep 1 '15 at 0:30
  • $\begingroup$ @OleksandrR. Can you show a usage example? I don't see how to use sequence when trying to splice in repeated copies of an element. $\endgroup$ – 1110101001 Sep 1 '15 at 0:32
  • 2
    $\begingroup$ Of course. {1, Sequence @@ ConstantArray[5, 3], 2} gives {1, 5, 5, 5, 2}. Define repeat[what_, times_] := Sequence @@ ConstantArray[what, times] and you can write {1, 2, 3, 4, repeat[5,3], 6, 7}, just like in the question. $\endgroup$ – Oleksandr R. Sep 1 '15 at 0:32
8
$\begingroup$

You can write your own repeat function like this:

repeat[m_, n_Integer?Positive] := Sequence @@ ConstantArray[m, n]

Then

{1, 2, 3, 4, repeat[5, 3], 6, 7}

evaluates to

{1, 2, 3, 4, 5, 5, 5, 6, 7}

The first argument can be anything.

{1, 2, 3, 4, repeat["anything", 2], 6, 7}
{1, 2, 3, 4, "anything", "anything", 6, 7}
$\endgroup$
  • 2
    $\begingroup$ I told my doctor, "When I do this it hurts". He told me, "Then don't do that". :P $\endgroup$ – m_goldberg Sep 1 '15 at 1:30

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