Commit 9cc43aa1 authored by Kevin Modzelewski's avatar Kevin Modzelewski

Implement sum() and dict.get

parent e1f070e0
......@@ -123,6 +123,21 @@ extern "C" Box* max2(Box* o0, Box* o1) {
return o0;
}
extern "C" Box* sum2(Box* container, Box* initial) {
if (initial->cls == str_cls)
raiseExcHelper(TypeError, "sum() can't sum strings [use ''.join(seq) instead]");
Box* cur = initial;
for (Box* e : container->pyElements()) {
cur = binop(cur, e, AST_TYPE::Add);
}
return cur;
}
extern "C" Box* sum1(Box* container) {
return sum2(container, boxInt(0));
}
extern "C" Box* open2(Box* arg1, Box* arg2) {
if (arg1->cls != str_cls) {
fprintf(stderr, "TypeError: coercing to Unicode: need string of buffer, %s found\n",
......@@ -406,6 +421,10 @@ void setupBuiltins() {
max_obj = new BoxedFunction(max_func);
builtins_module->giveAttr("max", max_obj);
CLFunction* sum_func = boxRTFunction((void*)sum1, NULL, 1, false);
addRTFunction(sum_func, (void*)sum2, NULL, 2, false);
builtins_module->giveAttr("sum", new BoxedFunction(sum_func));
chr_obj = new BoxedFunction(boxRTFunction((void*)chr, NULL, 1, false));
builtins_module->giveAttr("chr", chr_obj);
ord_obj = new BoxedFunction(boxRTFunction((void*)ord, NULL, 1, false));
......
......@@ -132,6 +132,21 @@ Box* dictPop3(BoxedDict* self, Box* k, Box* d) {
self->d.erase(it);
return rtn;
}
Box* dictGet3(BoxedDict* self, Box* k, Box* d) {
assert(self->cls == dict_cls);
auto it = self->d.find(k);
if (it == self->d.end())
return d;
return it->second;
}
Box* dictGet2(BoxedDict* self, Box* k) {
return dictGet3(self, k, None);
}
void setupDict() {
dict_cls->giveAttr("__name__", boxStrConstant("dict"));
// dict_cls->giveAttr("__len__", new BoxedFunction(boxRTFunction((void*)dictLen, NULL, 1, false)));
......@@ -154,6 +169,10 @@ void setupDict() {
addRTFunction(pop, (void*)dictPop3, UNKNOWN, 3, false);
dict_cls->giveAttr("pop", new BoxedFunction(pop));
CLFunction* get = boxRTFunction((void*)dictGet2, UNKNOWN, 2, false);
addRTFunction(get, (void*)dictGet3, UNKNOWN, 3, false);
dict_cls->giveAttr("get", new BoxedFunction(get));
dict_cls->giveAttr("__getitem__", new BoxedFunction(boxRTFunction((void*)dictGetitem, NULL, 2, false)));
dict_cls->giveAttr("__setitem__", new BoxedFunction(boxRTFunction((void*)dictSetitem, NULL, 3, false)));
......
......@@ -14,3 +14,15 @@ print __builtins__
print all([]), all([True]), all([False]), all([None]), all([True, False, None])
print any([]), any([True]), any([False]), any([None]), any([True, False, None])
print sum(range(5))
print sum(range(5), 5)
class C(object):
def __init__(self, n):
self.n = n
def __add__(self, rhs):
self.n = (self.n, rhs.n)
return self
print sum([C(1), C(2), C(3)], C(4)).n
......@@ -23,3 +23,7 @@ except KeyError, e:
print e.message
print "ok"
print sorted(d.items())
print d.get(4)
print d.get(4, 5)
print d.get(3, 5)
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