about summary refs log tree commit diff
path: root/src/libexpr
diff options
context:
space:
mode:
authorEelco Dolstra <eelco.dolstra@logicblox.com>2015-07-28T15·27+0200
committerEelco Dolstra <eelco.dolstra@logicblox.com>2015-07-28T15·28+0200
commit50807f3dd5241667dac0c0cc302042d648de4b42 (patch)
tree3f6222262e66b64c2dc7479f618e2beb78faca9a /src/libexpr
parentf3dda728a4a92520ec9db7bd28a184af9c07db0d (diff)
Add primop genList
This can be used to implement functions like ‘imap’ (or for that
matter, ‘map’) without the quadratic complexity incurred by calling
‘++’ repeatedly.
Diffstat (limited to 'src/libexpr')
-rw-r--r--src/libexpr/primops.cc20
1 files changed, 20 insertions, 0 deletions
diff --git a/src/libexpr/primops.cc b/src/libexpr/primops.cc
index ece76975d034..5da2f3463570 100644
--- a/src/libexpr/primops.cc
+++ b/src/libexpr/primops.cc
@@ -1364,6 +1364,25 @@ static void prim_all(EvalState & state, const Pos & pos, Value * * args, Value &
 }
 
 
+/* Apply a function to every element of a list. */
+static void prim_genList(EvalState & state, const Pos & pos, Value * * args, Value & v)
+{
+    state.forceFunction(*args[0], pos);
+    auto len = state.forceInt(*args[1], pos);
+
+    if (len < 0)
+        throw EvalError(format("cannot create list of size %1%, at %2%") % len % pos);
+
+    state.mkList(v, len);
+
+    for (unsigned int n = 0; n < len; ++n) {
+        Value * arg = state.allocValue();
+        mkInt(*arg, n);
+        mkApp(*(v.listElems()[n] = state.allocValue()), *args[0], *arg);
+    }
+}
+
+
 /*************************************************************
  * Integer arithmetic
  *************************************************************/
@@ -1759,6 +1778,7 @@ void EvalState::createBaseEnv()
     addPrimOp("__foldl'", 3, prim_foldlStrict);
     addPrimOp("__any", 2, prim_any);
     addPrimOp("__all", 2, prim_all);
+    addPrimOp("__genList", 2, prim_genList);
 
     // Integer arithmetic
     addPrimOp("__add", 2, prim_add);