# Define a function using pattern matching and repeated replacement to sum the elements of a list.(exercise in Paul Wellin's Book)

I am reading Paul Wellin "Essentials of Programming in Mathematica".

I have a question about his answer to 4.1 Exercise 5.

4.1 Exercise 5:

Define a function using pattern matching and repeated replacement to sum the elements of a list.

His answer is here:

sumList[lis_]:=First[lis//.{x_, y___} -> x + {y}]


I cannot understand why this function works correctly.

My wrong guess how his function works is here:

sumList[{1, 2, 3}]
=>
1 + {2, 3}
=>
1 + 2 + {3}
=>
1 + 2 + 3 + {}
=>
6 + {}
=>
{}


By the way,

sumList[lis_]:=First[lis/.{x_, y___} -> x + {y}]


also works correctly.

• Two things: note that x + {y} is automatically evaluated to {x + y}, and that x + y is internally represented as Plus[x, y]. – J. M. will be back soon Oct 18 '18 at 10:37
• Thank you again, J. M. is computer-less. But 0 + {} was evaluated to {}, not to {0} by Mathematica. – tchappy ha Oct 18 '18 at 10:48
• That sounds about right. Listable functions applied to {} will always yield {}, as there are no elements to map to. – J. M. will be back soon Oct 18 '18 at 10:54
• Thank you very much, J. M. is computer-less. Maybe I understand thanks to you. But why did Wellin write " repeated replacement" instead of "replacement"? – tchappy ha Oct 18 '18 at 11:05
• I guess he wanted the user to use //. somewhere in the solution. – J. M. will be back soon Oct 18 '18 at 11:06