mirror of
https://github.com/wren-lang/wren.git
synced 2026-01-11 22:28:45 +01:00
Use @munificent's single-argument reduce
This commit is contained in:
@ -29,7 +29,18 @@ class Sequence {
|
||||
return acc
|
||||
}
|
||||
|
||||
reduce(f) { this[1..-1].reduce(this[0], f) }
|
||||
reduce(f) {
|
||||
var iter = iterate(null)
|
||||
if (!iter) Fiber.abort("Can't reduce an empty sequence.")
|
||||
|
||||
// Seed with the first element.
|
||||
var result = iteratorValue(iter)
|
||||
while (iter = iterate(iter)) {
|
||||
result = f.call(result, iteratorValue(iter))
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@ -72,7 +72,18 @@ static const char* libSource =
|
||||
" return acc\n"
|
||||
" }\n"
|
||||
"\n"
|
||||
" reduce(f) { this[1..-1].reduce(this[0], f) }\n"
|
||||
" reduce(f) {\n"
|
||||
" var iter = iterate(null)\n"
|
||||
" if (!iter) Fiber.abort(\"Can't reduce an empty sequence.\")\n"
|
||||
"\n"
|
||||
" // Seed with the first element.\n"
|
||||
" var result = iteratorValue(iter)\n"
|
||||
" while (iter = iterate(iter)) {\n"
|
||||
" result = f.call(result, iteratorValue(iter))\n"
|
||||
" }\n"
|
||||
"\n"
|
||||
" return result\n"
|
||||
" }\n"
|
||||
"\n"
|
||||
"}\n"
|
||||
"\n"
|
||||
|
||||
@ -1 +1,2 @@
|
||||
[1].reduce {|a, b| a } // expect runtime error: Range start out of bounds.
|
||||
IO.print([1].reduce {|a, b| 42 }) // expect: 1
|
||||
IO.print([].reduce(1) {|a, b| 42 }) // expect: 1
|
||||
|
||||
Reference in New Issue
Block a user