Commit 525d95cc

525d95cc6ed5Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 2 files · ~2 modified

Description

Array#sum with a block

Sum the block's result over every element, with an optional initial value. Int accumulators use the overflow-aware sp_int_add; floats fold with the raw C operator. analyze types the block parameter as the element type and the result from the block's return type.

Co-Authored-By: Claude Opus 4.8 [email protected]

Details

Commit
525d95cc6ed5
Parent
f9015efe1332

src/analyze.cmodifiedView file

@@ -538,7 +538,15 @@
538538 if (!strcmp(name, "index") && (rt == TY_INT_ARRAY || rt == TY_STR_ARRAY)) return TY_POLY;
539539 if (!strcmp(name, "length") || !strcmp(name, "size") ||
540540 !strcmp(name, "count") || !strcmp(name, "index")) return TY_INT;
541- if (!strcmp(name, "sum")) return ty_array_elem(rt);
541+ if (!strcmp(name, "sum")) {
542+ int blk = nt_ref(nt, id, "block");
543+ if (blk >= 0) {
544+ int body = nt_ref(nt, blk, "body");
545+ int bn = 0; const int *bb = body >= 0 ? nt_arr(nt, body, "body", &bn) : NULL;
546+ return bn > 0 ? infer_type(c, bb[bn - 1]) : ty_array_elem(rt);
547+ }
548+ return ty_array_elem(rt);
549+ }
542550 if (!strcmp(name, "inject") || !strcmp(name, "reduce")) return ty_array_elem(rt);
543551 if (!strcmp(name, "tally") && argc == 0) {
544552 if (rt == TY_INT_ARRAY) return TY_INT_INT_HASH;
@@ -2032,6 +2040,7 @@
20322040 !strcmp(name, "max_by") || !strcmp(name, "min_by") || !strcmp(name, "sort_by") ||
20332041 !strcmp(name, "take_while") || !strcmp(name, "drop_while") ||
20342042 !strcmp(name, "reverse_each") || !strcmp(name, "each_entry") ||
2043+ !strcmp(name, "sum") ||
20352044 !strcmp(name, "each_with_index")) &&
20362045 ty_is_array(rt))
20372046 pt = ty_array_elem(rt);