0
$\begingroup$

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.

$\endgroup$
  • 2
    $\begingroup$ Two things: note that x + {y} is automatically evaluated to {x + y}, and that x + y is internally represented as Plus[x, y]. $\endgroup$ – J. M. will be back soon Oct 18 '18 at 10:37
  • $\begingroup$ Thank you again, J. M. is computer-less. But 0 + {} was evaluated to {}, not to {0} by Mathematica. $\endgroup$ – tchappy ha Oct 18 '18 at 10:48
  • 1
    $\begingroup$ That sounds about right. Listable functions applied to {} will always yield {}, as there are no elements to map to. $\endgroup$ – J. M. will be back soon Oct 18 '18 at 10:54
  • $\begingroup$ 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"? $\endgroup$ – tchappy ha Oct 18 '18 at 11:05
  • 2
    $\begingroup$ I guess he wanted the user to use //. somewhere in the solution. $\endgroup$ – J. M. will be back soon Oct 18 '18 at 11:06

Your Answer

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

Browse other questions tagged or ask your own question.