Skip to main content
added additional explanation
Source Link
rcollyer
  • 34.1k
  • 7
  • 94
  • 194

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}

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.

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}
Source Link
rcollyer
  • 34.1k
  • 7
  • 94
  • 194

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.