Jan 20, 2008

Tip: Programming Style

Read it from the company newsletter sometime ago:

Given a list of pairs of numbers, return a list consisting of the sum of each pair.
pairs = {{58, 96}, {85, 22}, {100, 69}, {5, 37}, {32, 64}, {41, 86}, {14, 0}, {79, 22}, {55, 36}, {86, 39}, {11, 15}};

(* Style I*)
result = Table[Null, {Length[pairs]}];
Do[result[[k]] = pairs[[k, 1]] + pairs[[k, 2]], {k, 1, Length[pairs]}]

result
(* Style II *)
Table[pairs[[k, 1]] + pairs[[k, 2]], {k, Length[pairs]}]
(* Style III *)
Apply[Plus, pairs, {1}]
(* Style IV *)
Map[Total, pairs]
(* Style V *)
pairs /. {p_, q_} -> p + q

(* Style VI *)
pairs[[All, 1]] + pairs[[All, 2]]

I work with Maltab most of the time,
it is useful to read this kind of document occasionally.

2 comments:

Anonymous said...

(*like style I*)
result = {};
Do[result = {result, pairs[[k, 1]] + pairs[[k, 2]]}, {k, 1, Length[pairs]}]
Flatten[result]


(*like style II*)
Table[k[[1]] + k[[2]], {k, pairs}]


(*like style III*)
Plus @@@ pairs


(*like style IV*)
Total /@ pairs

Anonymous said...

Even more like Matlab would be:
Total[Transpose[pairs]]