Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I am a beginner exploring the world of Mathematica. I expected the following code

T[6, 5, 4, 1, 2, 3] /. {T[a___, 1, b___] -> Length[List[b]]}

should return the value 2, rather than 1. Anyone could explain where I was wrong?

share|improve this question
3  
note that T is a bad choice of variable/function name. I suggest using names starting in lowercase letters, especially when using single letters. This avoids conflicts with built-ins (e.g. N, D...) –  Pinguin Dirk Apr 8 '13 at 8:26
add comment

2 Answers 2

up vote 11 down vote accepted

This is because the code Length[List[b]] is evaluated before the rule is applied. Using RuleDelayed rather than Rule would fix it:

T[6, 5, 4, 1, 2, 3] /. {T[a___, 1, b___] :> Length[{b}]}

share|improve this answer
add comment

The function Trace can be helpful in diagnosing the problem. The documentation says:

Trace returns a set of nested lists. Each individual list corresponds to a single evaluation chain, which contains the sequence of forms found for a particular expression. The list has sublists which give the histories of subsidiary evaluations.

With your input:

Trace[
  T[6, 5, 4, 1, 2, 3] /. {T[a___, 1, b___] -> Length[List[b]]}
]
{{{{Length[{b}],1},T[a___,1,b___]->1,T[a___,1,b___]->1},
 {T[a___,1,b___]->1}},T[6,5,4,1,2,3]/.{T[a___,1,b___]->1},1}

Observe that the first evaluation chain is {Length[{b}],1} which clearly shows the problem. Now compare the Trace when correctly using RuleDelayed:

Trace[
  T[6, 5, 4, 1, 2, 3] /. {T[a___, 1, b___] :> Length[List[b]]}
]
{{{T[a___,1,b___]:>Length[{b}],T[a___,1,b___]:>Length[{b}]},
{T[a___,1,b___]:>Length[{b}]}},T[6,5,4,1,2,3]/.
{T[a___,1,b___]:>Length[{b}]},Length[{2,3}],2}
share|improve this answer
    
Thank you. This would be very helpful to understand the behavior of Mathematica. –  Joonho Kim Apr 9 '13 at 23:23
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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