How to iterate or map over tuples?

Here’s an overly-clever macro solution: trait JoinTuple { fn join_tuple(&self, sep: &str) -> String; } macro_rules! tuple_impls { () => {}; ( ($idx:tt => $typ:ident), $( ($nidx:tt => $ntyp:ident), )* ) => { impl<$typ, $( $ntyp ),*> JoinTuple for ($typ, $( $ntyp ),*) where $typ: ::std::fmt::Display, $( $ntyp: ::std::fmt::Display ),* { fn join_tuple(&self, sep: &str) … Read more

Java: Array with loop

Here’s how: // Create an array with room for 100 integers int[] nums = new int[100]; // Fill it with numbers using a for-loop for (int i = 0; i < nums.length; i++) nums[i] = i + 1; // +1 since we want 1-100 and not 0-99 // Compute sum int sum = 0; for … Read more

Loop over DOMDocument

Try this: $doc = new DOMDocument(); $doc->loadHTML($html); showDOMNode($doc); function showDOMNode(DOMNode $domNode) { foreach ($domNode->childNodes as $node) { print $node->nodeName.’:’.$node->nodeValue; if($node->hasChildNodes()) { showDOMNode($node); } } }

Loop over 2 lists, repeating the shortest until end of longest [duplicate]

Assuming la is longer than lb: >>> import itertools >>> [x+’_’+y for x,y in zip(la, itertools.cycle(lb))] [‘a1_b1’, ‘a2_b2’, ‘a3_b1’, ‘a4_b2’] itertools.cycle(lb) returns a cyclic iterator for the elements in lb. zip(…) returns a list of tuples in which each element corresponds to an element in la coupled with the matching element in the iterator.

Javascript: hiding prototype methods in for loop?

You can achieve desired outcome from the other end by making the prototype methods not enumerable: Object.defineProperty(Array.prototype, “containsKey”, { enumerable: false, value: function(obj) { for(var key in this) if (key == obj) return true; return false; } }); This usually works better if you have control over method definitions, and in particular if you have … Read more

Node.js – Using the async lib – async.foreach with object

The final function does not get called because async.forEach requires that you call the callback function for every element. Use something like this: async.forEach(Object.keys(dataObj), function (item, callback){ console.log(item); // print the key // tell async that that particular element of the iterator is done callback(); }, function(err) { console.log(‘iterating done’); });

endforeach in loops?

It’s mainly so you can make start and end statements clearer when creating HTML in loops: <table> <? while ($record = mysql_fetch_assoc($rs)): ?> <? if (!$record[‘deleted’]): ?> <tr> <? foreach ($display_fields as $field): ?> <td><?= $record[$field] ?></td> <? endforeach; ?> <td> <select name=”action” onChange=”submit”> <? foreach ($actions as $action): ?> <option value=”<?= $action ?>”><?= $action … Read more