Commits

Anonymous committed 1ec3145

implement map, for some value of implement

Comments (0)

Files changed (2)

Lib/test/parrot/builtins.py

 repr_a = "[1, 2, 'hi']"
 if repr(a) == repr_a: print('success: repr (list)')
 else: print('xfail: repr (list)')                   # XXX
+
+#map
+print('test: map (builtin func)')
+a = [ 1, 2, 3, 4 ]
+b = [ '1', '2', '3', '4' ]
+res = map(str, a)
+ok = 1
+for i in range(4):
+    if res[i] != b[i]: ok = 0
+if ok: print('success: map (builtin func)')
+else:  print('failure: map (builtin func)')
+
+print('test: map (python func)')
+try:
+    a = [ 1, 2, 3, 4 ]
+    b = [ 2, 3, 4, 5 ]
+    def f(x): return x + 1
+    res = map(f, a)
+    for i in range(4):
+        assert res[i] == b[i]
+    print('success: map (builtin func)')
+except:
+    print('failure: map (builtin func)')

src/builtins/funcs.pir

     .param pmc list
     .param pmc args :slurpy
 
-    $P0 = new 'Exception'
-    $P0 = 'NotImplementedError'      # XXX
-    throw $P0
+    # XXX allow function to be None
+    # XXX return an iterator rather than a list (as per Python 3.0)
+
+    .local int num_lists
+    .local pmc result, list_array, iter_array, func_params
+
+    list_array = args
+    unshift list_array, list
+    num_lists = elements list_array
+
+    # Build list of iterators, one for each list
+    iter_array = new 'FixedPMCArray'
+    iter_array = num_lists
+    $I0 = 0
+make_iter_array_loop:
+    $P0 = list_array[$I0]
+    $P1 = new 'Iterator', $P0
+    iter_array[$I0] = $P1
+    inc $I0
+    unless $I0 >= num_lists goto make_iter_array_loop
+
+
+    # Now iterate over all the lists together
+    result = new 'ResizablePMCArray'
+loop:
+    func_params = new 'FixedPMCArray'
+    func_params = num_lists
+    
+    # get one element from each iterator
+    $I0 = 0
+make_func_params_loop:
+    $P0 = iter_array[$I0]
+    unless $P0 goto done      # stop when done iterating over any of the lists    
+    $P1 = shift $P0
+    func_params[$I0] = $P1
+    inc $I0
+    unless $I0 >= num_lists goto make_func_params_loop
+
+    # call function and add function result to result list
+    $P0 = function(func_params :flat)
+    push result, $P0
+    goto loop
+    
+done:
+    .return (result)
 .end