Commit e43a3743 authored by Joris Vankerschaver's avatar Joris Vankerschaver

Add tuple repeat.

parent 2f601718
...@@ -14,6 +14,7 @@ ...@@ -14,6 +14,7 @@
#include "runtime/tuple.h" #include "runtime/tuple.h"
#include <algorithm>
#include <sstream> #include <sstream>
#include "core/ast.h" #include "core/ast.h"
...@@ -127,6 +128,30 @@ Box* tupleAdd(BoxedTuple* self, Box* rhs) { ...@@ -127,6 +128,30 @@ Box* tupleAdd(BoxedTuple* self, Box* rhs) {
return new BoxedTuple(std::move(velts)); 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) { Box* tupleLen(BoxedTuple* t) {
assert(t->cls == tuple_cls); assert(t->cls == tuple_cls);
return boxInt(t->elts.size()); return boxInt(t->elts.size());
...@@ -389,6 +414,8 @@ void setupTuple() { ...@@ -389,6 +414,8 @@ void setupTuple() {
tuple_cls->giveAttr("__repr__", new BoxedFunction(boxRTFunction((void*)tupleRepr, STR, 1))); tuple_cls->giveAttr("__repr__", new BoxedFunction(boxRTFunction((void*)tupleRepr, STR, 1)));
tuple_cls->giveAttr("__str__", tuple_cls->getattr("__repr__")); tuple_cls->giveAttr("__str__", tuple_cls->getattr("__repr__"));
tuple_cls->giveAttr("__add__", new BoxedFunction(boxRTFunction((void*)tupleAdd, BOXED_TUPLE, 2))); 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(); tuple_cls->freeze();
......
...@@ -177,3 +177,24 @@ print bool((0,)) ...@@ -177,3 +177,24 @@ print bool((0,))
print bool((0, 0)) print bool((0, 0))
print (65, (1, 2, 3), 65) 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