Make a partition with a rule [duplicate]

This question already has an answer here:

Unexpected behavior of rule matching a pattern

2 answers

I wrote this line of code :

{{1, 1, 1}, {1, 1}} /. ((x___ /; Length[x] > 2) -> Partition[x, 2, 1])

generates this error :

Partition::pdep: Depth 1 requested in object with dimensions {}.

The questions are simple :
Is it possible to avoid this error ?
Are there any alternative ?

Thank you for your attention.

Edit

Thank you for your answers.
I did not realize the utility of RuleDelayed up to now .

=================

=================

2 Answers
2

=================

{{1, 1, 1}, {1, 1}} /.
a : {__Integer} /; Length[a] > 2 :> Partition[a, 2, 1]

{{{1, 1}, {1, 1}}, {1, 1}}

{{1, 2, 3, 4}, {1, 1}} /.
a : {__Integer} /; Length[a] > 2 :> Partition[a, 2, 1]

{{{1, 2}, {2, 3}, {3, 4}}, {1, 1}}

Alternative

Vectors of length 2 are not partitioned:

Partition[{1, 1}, 2, 1]

{{1, 1}}

But observe the extra brackets. If they don’t disturb you could more directly write:

res = Map[Partition[#, 2, 1] &, {{1, 2, 3, 4}, {8, 8}}]

{{{1, 2}, {2, 3}, {3, 4}}, {{8, 8}}}

If they disturb:

res /. {{a__}} :> {a}

{{{1, 2}, {2, 3}, {3, 4}}, {8, 8}}

This alternative should be faster with large lists.

Use RuleDelayed instead of Rule

{{1, 1, 1}, {1, 1}} /. ((x___ /; Length[x] > 2) :> Partition[x, 2, 1])