Commit 4f9e7751 authored by Kevin Modzelewski's avatar Kevin Modzelewski

Merge pull request #227 from jvkersch/fix-int-times-list

List right multiplication, tuple multiplication
parents 9dc01580 e43a3743
......@@ -593,6 +593,7 @@ void setupList() {
list_cls->giveAttr("insert", new BoxedFunction(boxRTFunction((void*)listInsert, NONE, 3)));
list_cls->giveAttr("__mul__", new BoxedFunction(boxRTFunction((void*)listMul, LIST, 2)));
list_cls->giveAttr("__rmul__", new BoxedFunction(boxRTFunction((void*)listMul, LIST, 2)));
list_cls->giveAttr("__iadd__", new BoxedFunction(boxRTFunction((void*)listIAdd, UNKNOWN, 2)));
list_cls->giveAttr("__add__", new BoxedFunction(boxRTFunction((void*)listAdd, UNKNOWN, 2)));
......
......@@ -14,6 +14,7 @@
#include "runtime/tuple.h"
#include <algorithm>
#include <sstream>
#include "core/ast.h"
......@@ -127,6 +128,30 @@ Box* tupleAdd(BoxedTuple* self, Box* rhs) {
return new BoxedTuple(std::move(velts));
}
Box* tupleMul(BoxedTuple* self, Box* rhs) {
if (rhs->cls != int_cls) {
raiseExcHelper(TypeError, "can't multiply sequence by non-int of type '%s'", getTypeName(rhs)->c_str());
}
int n = static_cast<BoxedInt*>(rhs)->n;
int s = self->elts.size();
if (n < 0)
n = 0;
if (s == 0 || n == 1) {
return self;
} else {
BoxedTuple::GCVector velts(n * s);
auto iter = velts.begin();
for (int i = 0; i < n; ++i) {
std::copy(self->elts.begin(), self->elts.end(), iter);
iter += s;
}
return new BoxedTuple(std::move(velts));
}
}
Box* tupleLen(BoxedTuple* t) {
assert(t->cls == tuple_cls);
return boxInt(t->elts.size());
......@@ -389,6 +414,8 @@ void setupTuple() {
tuple_cls->giveAttr("__repr__", new BoxedFunction(boxRTFunction((void*)tupleRepr, STR, 1)));
tuple_cls->giveAttr("__str__", tuple_cls->getattr("__repr__"));
tuple_cls->giveAttr("__add__", new BoxedFunction(boxRTFunction((void*)tupleAdd, BOXED_TUPLE, 2)));
tuple_cls->giveAttr("__mul__", new BoxedFunction(boxRTFunction((void*)tupleMul, BOXED_TUPLE, 2)));
tuple_cls->giveAttr("__rmul__", new BoxedFunction(boxRTFunction((void*)tupleMul, BOXED_TUPLE, 2)));
tuple_cls->freeze();
......
......@@ -71,3 +71,8 @@ while l:
l = range(5)
l.extend(range(5))
print l
# Repeating a list
x = [0, 1, 2]
print 2 * x
print x * 2
......@@ -177,3 +177,24 @@ print bool((0,))
print bool((0, 0))
print (65, (1, 2, 3), 65)
# Multiplying a tuple by an integer
x = (1, 2, 3)
print x * -1
print x * 0
print x * 1
print x * 5
print -1 * x
print 0 * x
print 1 * x
print 5 * x
x = ()
print x * -1
print x * 0
print x * 1
print x * 5
print -1 * x
print 0 * x
print 1 * x
print 5 * x
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment