From 61af14a9219bff090b238f15c9def5453087aa5d Mon Sep 17 00:00:00 2001 From: Eelco Dolstra Date: Thu, 23 Jul 2015 17:03:02 +0200 Subject: [PATCH] Add foldl' primop --- doc/manual/expressions/builtins.xml | 13 +++++++++++++ src/libexpr/primops.cc | 24 ++++++++++++++++++++++++ tests/lang/lib.nix | 2 +- 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/doc/manual/expressions/builtins.xml b/doc/manual/expressions/builtins.xml index 6bdfdd55c..0b11e2f5a 100644 --- a/doc/manual/expressions/builtins.xml +++ b/doc/manual/expressions/builtins.xml @@ -313,6 +313,19 @@ stdenv.mkDerivation { + builtins.foldl’ + op nul list + + Reduce a list by applying a binary operator, from + left to right, e.g. foldl’ op nul [x0 x1 x2 ...] = op (op + (op nul x0) x1) x2) .... The operator is applied + strictly, i.e., its arguments are evaluated first. For example, + foldl’ (x: y: x + y) 0 [1 2 3] evaluates to + 6. + + + + builtins.fromJSON e Convert a JSON string to a Nix diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc index c36a68ce0..6a4b5b042 100644 --- a/src/libexpr/primops.cc +++ b/src/libexpr/primops.cc @@ -1304,6 +1304,29 @@ static void prim_length(EvalState & state, const Pos & pos, Value * * args, Valu } +/* Reduce a list by applying a binary operator, from left to + right. The operator is applied strictly. */ +static void prim_foldlStrict(EvalState & state, const Pos & pos, Value * * args, Value & v) +{ + state.forceFunction(*args[0], pos); + state.forceList(*args[2], pos); + + Value * vCur = args[1]; + + if (args[2]->list.length) + for (unsigned int n = 0; n < args[2]->list.length; ++n) { + Value vTmp; + state.callFunction(*args[0], *vCur, vTmp, pos); + vCur = n == args[2]->list.length - 1 ? &v : state.allocValue(); + state.callFunction(vTmp, *args[2]->list.elems[n], *vCur, pos); + } + else + v = *vCur; + + state.forceValue(v); +} + + /************************************************************* * Integer arithmetic *************************************************************/ @@ -1641,6 +1664,7 @@ void EvalState::createBaseEnv() addPrimOp("__elem", 2, prim_elem); addPrimOp("__concatLists", 1, prim_concatLists); addPrimOp("__length", 1, prim_length); + addPrimOp("__foldl'", 3, prim_foldlStrict); // Integer arithmetic addPrimOp("__add", 2, prim_add); diff --git a/tests/lang/lib.nix b/tests/lang/lib.nix index 882005dc1..262cdd7e8 100644 --- a/tests/lang/lib.nix +++ b/tests/lang/lib.nix @@ -17,7 +17,7 @@ rec { then fold (x: y: (flatten x) ++ y) [] x else [x]; - sum = fold (x: y: add x y) 0; + sum = foldl' (x: y: add x y) 0; hasSuffix = ext: fileName: let lenFileName = stringLength fileName;