Ticket #126 (accepted enhancement)
Provide enumerate method (or similar) in CobraCore
Reported by: | hopscc | Owned by: | Chuck |
---|---|---|---|
Priority: | medium | Milestone: | |
Component: | Cobra Compiler | Version: | 0.8.0 |
Keywords: | Cc: |
Description
Once you have multi arg assignment in for loops it seems its a common idiom to want to walk an IEnumerable and get back an item and its offset in the IEnumerable
Currently to do this you need to wrap a counter around the IEnumerable forloop
i as int = 0 for item in mylist doSomethingWith(i, item) i += 1
While not difficult this is tedious and obscurative and generally 'clunky'
In python this is provided with an .enumerate function
myList = [ 'one", 'two', 'three'] for i, item in enumerate(myList) doSomethingWith(i, item)
I propose we add a similar method to CobraCore
allowing something like
myList = [ 'one", 'two', 'three'] for i, item in CobraCore.enumerate(myList) doSomethingWith(i, item)
Pending pure functions or some form of default method lookup to
a specified class ( CobraCore ) this is probably as simple as we can get....
Heres the implementation
def enumerate(ie as IEnumerable) as IEnumerable<of IList> is shared n=0 for e in ie yield [n, e] n += 1 def main is shared a = [1,2,3,4] l = .enumerate(a) l1 = for ii in l get ii assert l1 == [[0,1],[1,2],[2,3],[3,4]] for i,item in .enumerate(['a','b','c']) assert i in [0,1,2] assert item in ['a', 'b', 'c'] #print "[i]:[item]" kvpList = [KeyValuePair<of String, String>('x','aa'), KeyValuePair<of String, String>('y','bb'), KeyValuePair<of String, String>('z','cc') ] for i,kv in .enumerate({'x':'aa','y':'bb','z':'cc'}) assert i in [0,1,2] assert kv in kvpList #print "[i]:[kv]"
Change History
Note: See
TracTickets for help on using
tickets.