Iterable emulation in transcript

I am trying to port a vector math library to transcrypt and I am facing a duplicate type emulation problem.

I have a Vector class with internal iteration. Here's a simplified version of the kernel:

class Vector:
    def __init__(self, *values):
        self.values = values

    def __iter__(self):
        for item in self.values:
            yield item

    def __add__(self, other):
        return Vector( *(x + y for x, y in zip(self, other)))

      

In pure python, it (Vector(1,2,3) + Vector(3,4,5))

returns Vector(4,6,8)

as you'd expect. But after re-coding, the same code fails - in Javascript it seems to zip()

expect a Javascript function map()

on its iterable objects.

I can work around this in this case by explicitly targeting the underlying store, which, since it was created with * args, seems to have the required method:

def __add__(self, other):
    pairwise = zip(self.values, other.values)
    return Vector( *(itertools.starmap(lambda a, b: a + b, pairwise)))

      

but connecting to an inner container seems to be risky to me and I guess there is an overhead for creating an iterator and a starmap.

So - what's the correct way to get around this? Can I add a class map()

to a class? And if so, what is the correct signature? Foundational JS seems to rely on JS behavior that scares me ...

+3


source to share


1 answer


The point is, it zip

is not yet adapted for iterators. A simple workaround is to convert the arguments zip

to lists. The following code works:

class Vector:
    def __init__(self, *values):
        self.values = values

    def __iter__(self):
        for item in self.values:
            yield item

    def __add__(self, other):
        return Vector( *(x + y for x, y in zip(list (self), list (other))))

    def __str__ (self):
        return self.values

#__pragma__ ('opov')

print (Vector(1,2,3) + Vector(3,4,5))

#__pragma__ ('noopov')

      

This will print:

4,6,8

      



Sorry for the late reply, a little drained in the last few months. Adapting zip for iterators I found quite difficult, so it hasn't been done yet.

Think about it, converting parameters to lists can be done automatically. I'll add this (issue # 369) despite the (tiny) run-time test overhead because it better matches the expected behavior.

This is in version 3.6.44 and your code should now work correctly without changes (using the -e 6 switch to activate iterators).

0


source







All Articles