summary refs log tree commit diff stats
path: root/lib/pure/collections
diff options
context:
space:
mode:
authorFredrik Høisæther Rasch <fredrik.h.rasch@uit.no>2017-11-08 15:18:45 +0100
committerAndreas Rumpf <rumpf_a@web.de>2017-11-18 14:18:00 +0100
commitb02ecda5a052b828d8baed3ba6ff1ce58b660a44 (patch)
treed853d2bb985e4e104abe16d77821d05480c14586 /lib/pure/collections
parentbd2f4d18525d9242183d17ec33730c684af6d698 (diff)
downloadNim-b02ecda5a052b828d8baed3ba6ff1ce58b660a44.tar.gz
Move asArray macro back to sequtils
This reverts commit 72f653c2daa5c629ed8a57a4f53dcef56432aa26.
Diffstat (limited to 'lib/pure/collections')
-rw-r--r--lib/pure/collections/sequtils.nim30
1 files changed, 30 insertions, 0 deletions
diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim
index 0eb8e6704..ee89ce17b 100644
--- a/lib/pure/collections/sequtils.nim
+++ b/lib/pure/collections/sequtils.nim
@@ -20,6 +20,8 @@
 
 include "system/inclrtl"
 
+import macros
+
 when not defined(nimhygiene):
   {.pragma: dirty.}
 
@@ -704,6 +706,28 @@ template newSeqWith*(len: int, init: untyped): untyped =
     result[i] = init
   result
 
+macro asArray*(targetType: untyped, values: typed): untyped =
+  ## applies a type conversion to each of the elements in the specified
+  ## array literal. Each element is converted to the ``targetType`` type..
+  ##
+  ## Example:
+  ##
+  ## .. code-block::
+  ##   let x = asArray(int, [0.1, 1.2, 2.3, 3.4])
+  ##   doAssert x is array[4, int]
+  ##
+  ## Short notation for:
+  ##
+  ## .. code-block::
+  ##   let x = [(0.1).int, (1.2).int, (2.3).int, (3.4).int]
+  values.expectKind(nnkBracket)
+  result = newNimNode(nnkBracket, lineInfoFrom=values)
+  for i in 0 ..< len(values):
+    var call = newNimNode(nnkCall, lineInfoFrom=values[i])
+    call.add targetType
+    call.add values[i]
+    result.add call
+
 when isMainModule:
   import strutils
   block: # concat test
@@ -992,5 +1016,11 @@ when isMainModule:
     seq2D[0][1] = true
     doAssert seq2D == @[@[true, true], @[true, false], @[false, false], @[false, false]]
 
+  block: # asArray tests
+    let x = asArray(int, [1.2, 2.3, 3.4, 4.5])
+    doAssert x is array[4, int]
+    let y = asArray(`$`, [1.2, 2.3, 3.4, 4.5])
+    doAssert y is array[4, string]
+
   when not defined(testing):
     echo "Finished doc tests"