Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/stevedonovan/Penlight.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorsteve donovan <steve.j.donovan@gmail.com>2011-09-20 17:45:37 +0400
committersteve donovan <steve.j.donovan@gmail.com>2011-09-20 17:45:37 +0400
commit87ab927a44861c9158c8e8fafbf2bc084b9836f1 (patch)
tree918b19b0df0d3637528c6b2739f4dbb7db08d279
parente311315c43aedb1e121151482ae23dcd2671d282 (diff)
fix by Carl Adahl to seq.reduce: correct order of reduction
-rw-r--r--lua/pl/seq.lua25
-rw-r--r--tests/test-seq.lua1
2 files changed, 15 insertions, 11 deletions
diff --git a/lua/pl/seq.lua b/lua/pl/seq.lua
index 7d7f57f..1535be0 100644
--- a/lua/pl/seq.lua
+++ b/lua/pl/seq.lua
@@ -352,19 +352,22 @@ function seq.filter (iter,pred,arg)
end
--- 'reduce' a sequence using a binary function.
--- @param seq a sequence
-- @param fun a function of two arguments
+-- @param iter a sequence
+-- @param oldval optional initial value
-- @usage seq.reduce(operator.add,seq.list{1,2,3,4}) == 10
-function seq.reduce (fun,seq,oldval)
- if not oldval then
- seq = default_iter(seq)
- oldval = seq()
- fun = function_arg(1,fun)
- end
- local val = seq()
- if val==nil then return oldval
- else return fun(oldval,seq.reduce(fun,seq,val))
- end
+-- @usage seq.reduce('-',{1,2,3,4,5}) == -13
+function seq.reduce (fun,iter,oldval)
+ fun = function_arg(1,fun)
+ iter = default_iter(iter)
+ if not oldval then
+ oldval = iter()
+ end
+ local val = oldval
+ for v in iter do
+ val = fun(val,v)
+ end
+ return val
end
--- take the first n values from the sequence.
diff --git a/tests/test-seq.lua b/tests/test-seq.lua
index 2bd61c7..fa13067 100644
--- a/tests/test-seq.lua
+++ b/tests/test-seq.lua
@@ -25,6 +25,7 @@ asserteq(
{20,15}
)
+asserteq(seq.reduce('-',{1,2,3,4,5}),-13)
asserteq(seq.count(S{10,20,30,40},L'|x| x > 20'), 2)