How can I name a repeated pattern to apply a rule on it? In the example below I have two element sequence. There is no problem in naming them and then applying some function on it:

SequenceReplace[{1, 1, 2, 3, 4, 5}, {a_, b_} /; b > 1.2 a :> 
  f[{a, b}]]

What if the length of the sequence is variable, say of size k with some constraint on that pattern {_,_ ,etc}? There is Repeated[_, {k}]. But how to pass it to the function f?


The first thing to note is that a_ is a short hand notation. It is almost always helpful to look at the FullForm when you are trying to write patterns. When you do that with a_ you will notice that it is interpreted as

Pattern[a, Blank[]]

From the docs, this can be written as

a: _

This provides a way to name repeated sequences, e.g.

a : Repeated[_, {k}] (* where k has to be a positive integer *)
c : {a_, b_}
c : {a_, b : Repeated[_, {k}]}

or any other pattern you wish.

As an additional note, when using a in

a : Repeated[_, {k}]

it is a Sequence, and a typical method for manipulating it is to place it inside of a List, e.g.

(* the simplest example *)
f[a : Repeated[_, {k}]] := {a}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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