sequtils.nim 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2011 Alexander Mitchell-Robinson
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Although this module has `seq` in its name, it implements operations
  10. ## not only for the `seq`:idx: type, but for three built-in container types
  11. ## under the `openArray` umbrella:
  12. ## * sequences
  13. ## * strings
  14. ## * array
  15. ##
  16. ## The `system` module defines several common functions, such as:
  17. ## * `newSeq[T]` for creating new sequences of type `T`
  18. ## * `@` for converting arrays and strings to sequences
  19. ## * `add` for adding new elements to strings and sequences
  20. ## * `&` for string and seq concatenation
  21. ## * `in` (alias for `contains`) and `notin` for checking if an item is
  22. ## in a container
  23. ##
  24. ## This module builds upon that, providing additional functionality in form of
  25. ## procs, iterators and templates inspired by functional programming
  26. ## languages.
  27. ##
  28. ## For functional style programming you have different options at your disposal:
  29. ## * the `sugar.collect macro<sugar.html#collect.m%2Cuntyped%2Cuntyped>`_
  30. ## * pass an `anonymous proc<manual.html#procedures-anonymous-procs>`_
  31. ## * import the `sugar module<sugar.html>`_ and use
  32. ## the `=> macro<sugar.html#%3D>.m,untyped,untyped>`_
  33. ## * use `...It templates<#18>`_
  34. ## (`mapIt<#mapIt.t,typed,untyped>`_,
  35. ## `filterIt<#filterIt.t,untyped,untyped>`_, etc.)
  36. ##
  37. ## Chaining of functions is possible thanks to the
  38. ## `method call syntax<manual.html#procedures-method-call-syntax>`_.
  39. runnableExamples:
  40. import std/sugar
  41. # Creating a sequence from 1 to 10, multiplying each member by 2,
  42. # keeping only the members which are not divisible by 6.
  43. let
  44. foo = toSeq(1..10).map(x => x * 2).filter(x => x mod 6 != 0)
  45. bar = toSeq(1..10).mapIt(it * 2).filterIt(it mod 6 != 0)
  46. baz = collect:
  47. for i in 1..10:
  48. let j = 2 * i
  49. if j mod 6 != 0:
  50. j
  51. doAssert foo == bar
  52. doAssert foo == baz
  53. doAssert foo == @[2, 4, 8, 10, 14, 16, 20]
  54. doAssert foo.any(x => x > 17)
  55. doAssert not bar.allIt(it < 20)
  56. doAssert foo.foldl(a + b) == 74 # sum of all members
  57. runnableExamples:
  58. from std/strutils import join
  59. let
  60. vowels = @"aeiou"
  61. foo = "sequtils is an awesome module"
  62. doAssert (vowels is seq[char]) and (vowels == @['a', 'e', 'i', 'o', 'u'])
  63. doAssert foo.filterIt(it notin vowels).join == "sqtls s n wsm mdl"
  64. ## See also
  65. ## ========
  66. ## * `strutils module<strutils.html>`_ for common string functions
  67. ## * `sugar module<sugar.html>`_ for syntactic sugar macros
  68. ## * `algorithm module<algorithm.html>`_ for common generic algorithms
  69. ## * `json module<json.html>`_ for a structure which allows
  70. ## heterogeneous members
  71. import std/private/since
  72. import std/macros
  73. from std/typetraits import supportsCopyMem
  74. when defined(nimPreviewSlimSystem):
  75. import std/assertions
  76. when defined(nimHasEffectsOf):
  77. {.experimental: "strictEffects".}
  78. else:
  79. {.pragma: effectsOf.}
  80. macro evalOnceAs(expAlias, exp: untyped,
  81. letAssigneable: static[bool]): untyped =
  82. ## Injects `expAlias` in caller scope, to avoid bugs involving multiple
  83. ## substitution in macro arguments such as
  84. ## https://github.com/nim-lang/Nim/issues/7187.
  85. ## `evalOnceAs(myAlias, myExp)` will behave as `let myAlias = myExp`
  86. ## except when `letAssigneable` is false (e.g. to handle openArray) where
  87. ## it just forwards `exp` unchanged.
  88. expectKind(expAlias, nnkIdent)
  89. var val = exp
  90. result = newStmtList()
  91. # If `exp` is not a symbol we evaluate it once here and then use the temporary
  92. # symbol as alias
  93. if exp.kind != nnkSym and letAssigneable:
  94. val = genSym()
  95. result.add(newLetStmt(val, exp))
  96. result.add(
  97. newProc(name = genSym(nskTemplate, $expAlias), params = [getType(untyped)],
  98. body = val, procType = nnkTemplateDef))
  99. func concat*[T](seqs: varargs[seq[T]]): seq[T] =
  100. ## Takes several sequences' items and returns them inside a new sequence.
  101. ## All sequences must be of the same type.
  102. ##
  103. ## **See also:**
  104. ## * `distribute func<#distribute,seq[T],Positive>`_ for a reverse
  105. ## operation
  106. ##
  107. runnableExamples:
  108. let
  109. s1 = @[1, 2, 3]
  110. s2 = @[4, 5]
  111. s3 = @[6, 7]
  112. total = concat(s1, s2, s3)
  113. assert total == @[1, 2, 3, 4, 5, 6, 7]
  114. var L = 0
  115. for seqitm in items(seqs): inc(L, len(seqitm))
  116. newSeq(result, L)
  117. var i = 0
  118. for s in items(seqs):
  119. for itm in items(s):
  120. result[i] = itm
  121. inc(i)
  122. func addUnique*[T](s: var seq[T], x: sink T) =
  123. ## Adds `x` to the container `s` if it is not already present.
  124. ## Uses `==` to check if the item is already present.
  125. runnableExamples:
  126. var a = @[1, 2, 3]
  127. a.addUnique(4)
  128. a.addUnique(4)
  129. assert a == @[1, 2, 3, 4]
  130. for i in 0..high(s):
  131. if s[i] == x: return
  132. when declared(ensureMove):
  133. s.add ensureMove(x)
  134. else:
  135. s.add x
  136. func count*[T](s: openArray[T], x: T): int =
  137. ## Returns the number of occurrences of the item `x` in the container `s`.
  138. ##
  139. runnableExamples:
  140. let
  141. a = @[1, 2, 2, 3, 2, 4, 2]
  142. b = "abracadabra"
  143. assert count(a, 2) == 4
  144. assert count(a, 99) == 0
  145. assert count(b, 'r') == 2
  146. for itm in items(s):
  147. if itm == x:
  148. inc result
  149. func cycle*[T](s: openArray[T], n: Natural): seq[T] =
  150. ## Returns a new sequence with the items of the container `s` repeated
  151. ## `n` times.
  152. ## `n` must be a non-negative number (zero or more).
  153. ##
  154. runnableExamples:
  155. let
  156. s = @[1, 2, 3]
  157. total = s.cycle(3)
  158. assert total == @[1, 2, 3, 1, 2, 3, 1, 2, 3]
  159. result = newSeq[T](n * s.len)
  160. var o = 0
  161. for x in 0 ..< n:
  162. for e in s:
  163. result[o] = e
  164. inc o
  165. proc repeat*[T](x: T, n: Natural): seq[T] =
  166. ## Returns a new sequence with the item `x` repeated `n` times.
  167. ## `n` must be a non-negative number (zero or more).
  168. ##
  169. runnableExamples:
  170. let
  171. total = repeat(5, 3)
  172. assert total == @[5, 5, 5]
  173. result = newSeq[T](n)
  174. for i in 0 ..< n:
  175. result[i] = x
  176. func deduplicate*[T](s: openArray[T], isSorted: bool = false): seq[T] =
  177. ## Returns a new sequence without duplicates.
  178. ##
  179. ## Setting the optional argument `isSorted` to true (default: false)
  180. ## uses a faster algorithm for deduplication.
  181. ##
  182. runnableExamples:
  183. let
  184. dup1 = @[1, 1, 3, 4, 2, 2, 8, 1, 4]
  185. dup2 = @["a", "a", "c", "d", "d"]
  186. unique1 = deduplicate(dup1)
  187. unique2 = deduplicate(dup2, isSorted = true)
  188. assert unique1 == @[1, 3, 4, 2, 8]
  189. assert unique2 == @["a", "c", "d"]
  190. result = @[]
  191. if s.len > 0:
  192. if isSorted:
  193. var prev = s[0]
  194. result.add(prev)
  195. for i in 1..s.high:
  196. if s[i] != prev:
  197. prev = s[i]
  198. result.add(prev)
  199. else:
  200. for itm in items(s):
  201. if not result.contains(itm): result.add(itm)
  202. func minIndex*[T](s: openArray[T]): int {.since: (1, 1).} =
  203. ## Returns the index of the minimum value of `s`.
  204. ## `T` needs to have a `<` operator.
  205. runnableExamples:
  206. let
  207. a = @[1, 2, 3, 4]
  208. b = @[6, 5, 4, 3]
  209. c = [2, -7, 8, -5]
  210. d = "ziggy"
  211. assert minIndex(a) == 0
  212. assert minIndex(b) == 3
  213. assert minIndex(c) == 1
  214. assert minIndex(d) == 2
  215. for i in 1..high(s):
  216. if s[i] < s[result]: result = i
  217. func maxIndex*[T](s: openArray[T]): int {.since: (1, 1).} =
  218. ## Returns the index of the maximum value of `s`.
  219. ## `T` needs to have a `<` operator.
  220. runnableExamples:
  221. let
  222. a = @[1, 2, 3, 4]
  223. b = @[6, 5, 4, 3]
  224. c = [2, -7, 8, -5]
  225. d = "ziggy"
  226. assert maxIndex(a) == 3
  227. assert maxIndex(b) == 0
  228. assert maxIndex(c) == 2
  229. assert maxIndex(d) == 0
  230. for i in 1..high(s):
  231. if s[i] > s[result]: result = i
  232. func minmax*[T](x: openArray[T]): (T, T) =
  233. ## The minimum and maximum values of `x`. `T` needs to have a `<` operator.
  234. var l = x[0]
  235. var h = x[0]
  236. for i in 1..high(x):
  237. if x[i] < l: l = x[i]
  238. if h < x[i]: h = x[i]
  239. result = (l, h)
  240. template zipImpl(s1, s2, retType: untyped): untyped =
  241. proc zip*[S, T](s1: openArray[S], s2: openArray[T]): retType =
  242. ## Returns a new sequence with a combination of the two input containers.
  243. ##
  244. ## The input containers can be of different types.
  245. ## If one container is shorter, the remaining items in the longer container
  246. ## are discarded.
  247. ##
  248. ## **Note**: For Nim 1.0.x and older version, `zip` returned a seq of
  249. ## named tuples with fields `a` and `b`. For Nim versions 1.1.x and newer,
  250. ## `zip` returns a seq of unnamed tuples.
  251. runnableExamples:
  252. let
  253. short = @[1, 2, 3]
  254. long = @[6, 5, 4, 3, 2, 1]
  255. words = @["one", "two", "three"]
  256. letters = "abcd"
  257. zip1 = zip(short, long)
  258. zip2 = zip(short, words)
  259. assert zip1 == @[(1, 6), (2, 5), (3, 4)]
  260. assert zip2 == @[(1, "one"), (2, "two"), (3, "three")]
  261. assert zip1[2][0] == 3
  262. assert zip2[1][1] == "two"
  263. when (NimMajor, NimMinor) <= (1, 0):
  264. let
  265. zip3 = zip(long, letters)
  266. assert zip3 == @[(a: 6, b: 'a'), (5, 'b'), (4, 'c'), (3, 'd')]
  267. assert zip3[0].b == 'a'
  268. else:
  269. let
  270. zip3: seq[tuple[num: int, letter: char]] = zip(long, letters)
  271. assert zip3 == @[(6, 'a'), (5, 'b'), (4, 'c'), (3, 'd')]
  272. assert zip3[0].letter == 'a'
  273. var m = min(s1.len, s2.len)
  274. newSeq(result, m)
  275. for i in 0 ..< m:
  276. result[i] = (s1[i], s2[i])
  277. when (NimMajor, NimMinor) <= (1, 0):
  278. zipImpl(s1, s2, seq[tuple[a: S, b: T]])
  279. else:
  280. zipImpl(s1, s2, seq[(S, T)])
  281. proc unzip*[S, T](s: openArray[(S, T)]): (seq[S], seq[T]) {.since: (1, 1).} =
  282. ## Returns a tuple of two sequences split out from a sequence of 2-field tuples.
  283. runnableExamples:
  284. let
  285. zipped = @[(1, 'a'), (2, 'b'), (3, 'c')]
  286. unzipped1 = @[1, 2, 3]
  287. unzipped2 = @['a', 'b', 'c']
  288. assert zipped.unzip() == (unzipped1, unzipped2)
  289. assert zip(unzipped1, unzipped2).unzip() == (unzipped1, unzipped2)
  290. result = (newSeq[S](s.len), newSeq[T](s.len))
  291. for i in 0..<s.len:
  292. result[0][i] = s[i][0]
  293. result[1][i] = s[i][1]
  294. func distribute*[T](s: seq[T], num: Positive, spread = true): seq[seq[T]] =
  295. ## Splits and distributes a sequence `s` into `num` sub-sequences.
  296. ##
  297. ## Returns a sequence of `num` sequences. For *some* input values this is the
  298. ## inverse of the `concat <#concat,varargs[seq[T]]>`_ func.
  299. ## The input sequence `s` can be empty, which will produce
  300. ## `num` empty sequences.
  301. ##
  302. ## If `spread` is false and the length of `s` is not a multiple of `num`, the
  303. ## func will max out the first sub-sequence with `1 + len(s) div num`
  304. ## entries, leaving the remainder of elements to the last sequence.
  305. ##
  306. ## On the other hand, if `spread` is true, the func will distribute evenly
  307. ## the remainder of the division across all sequences, which makes the result
  308. ## more suited to multithreading where you are passing equal sized work units
  309. ## to a thread pool and want to maximize core usage.
  310. ##
  311. runnableExamples:
  312. let numbers = @[1, 2, 3, 4, 5, 6, 7]
  313. assert numbers.distribute(3) == @[@[1, 2, 3], @[4, 5], @[6, 7]]
  314. assert numbers.distribute(3, false) == @[@[1, 2, 3], @[4, 5, 6], @[7]]
  315. assert numbers.distribute(6)[0] == @[1, 2]
  316. assert numbers.distribute(6)[1] == @[3]
  317. if num < 2:
  318. result = @[s]
  319. return
  320. # Create the result and calculate the stride size and the remainder if any.
  321. result = newSeq[seq[T]](num)
  322. var
  323. stride = s.len div num
  324. first = 0
  325. last = 0
  326. extra = s.len mod num
  327. if extra == 0 or spread == false:
  328. # Use an algorithm which overcounts the stride and minimizes reading limits.
  329. if extra > 0: inc(stride)
  330. for i in 0 ..< num:
  331. result[i] = newSeq[T]()
  332. for g in first ..< min(s.len, first + stride):
  333. result[i].add(s[g])
  334. first += stride
  335. else:
  336. # Use an undercounting algorithm which *adds* the remainder each iteration.
  337. for i in 0 ..< num:
  338. last = first + stride
  339. if extra > 0:
  340. extra -= 1
  341. inc(last)
  342. result[i] = newSeq[T]()
  343. for g in first ..< last:
  344. result[i].add(s[g])
  345. first = last
  346. proc map*[T, S](s: openArray[T], op: proc (x: T): S {.closure.}):
  347. seq[S] {.inline, effectsOf: op.} =
  348. ## Returns a new sequence with the results of the `op` proc applied to every
  349. ## item in the container `s`.
  350. ##
  351. ## Since the input is not modified, you can use it to
  352. ## transform the type of the elements in the input container.
  353. ##
  354. ## Instead of using `map` and `filter`, consider using the `collect` macro
  355. ## from the `sugar` module.
  356. ##
  357. ## **See also:**
  358. ## * `sugar.collect macro<sugar.html#collect.m%2Cuntyped%2Cuntyped>`_
  359. ## * `mapIt template<#mapIt.t,typed,untyped>`_
  360. ## * `apply proc<#apply,openArray[T],proc(T)_2>`_ for the in-place version
  361. ##
  362. runnableExamples:
  363. let
  364. a = @[1, 2, 3, 4]
  365. b = map(a, proc(x: int): string = $x)
  366. assert b == @["1", "2", "3", "4"]
  367. newSeq(result, s.len)
  368. for i in 0 ..< s.len:
  369. result[i] = op(s[i])
  370. proc apply*[T](s: var openArray[T], op: proc (x: var T) {.closure.})
  371. {.inline, effectsOf: op.} =
  372. ## Applies `op` to every item in `s`, modifying it directly.
  373. ##
  374. ## Note that the container `s` must be declared as a `var`,
  375. ## since `s` is modified in-place.
  376. ## The parameter function takes a `var T` type parameter.
  377. ##
  378. ## **See also:**
  379. ## * `applyIt template<#applyIt.t,untyped,untyped>`_
  380. ## * `map proc<#map,openArray[T],proc(T)>`_
  381. ##
  382. runnableExamples:
  383. var a = @["1", "2", "3", "4"]
  384. apply(a, proc(x: var string) = x &= "42")
  385. assert a == @["142", "242", "342", "442"]
  386. for i in 0 ..< s.len: op(s[i])
  387. proc apply*[T](s: var openArray[T], op: proc (x: T): T {.closure.})
  388. {.inline, effectsOf: op.} =
  389. ## Applies `op` to every item in `s` modifying it directly.
  390. ##
  391. ## Note that the container `s` must be declared as a `var`
  392. ## and it is required for your input and output types to
  393. ## be the same, since `s` is modified in-place.
  394. ## The parameter function takes and returns a `T` type variable.
  395. ##
  396. ## **See also:**
  397. ## * `applyIt template<#applyIt.t,untyped,untyped>`_
  398. ## * `map proc<#map,openArray[T],proc(T)>`_
  399. ##
  400. runnableExamples:
  401. var a = @["1", "2", "3", "4"]
  402. apply(a, proc(x: string): string = x & "42")
  403. assert a == @["142", "242", "342", "442"]
  404. for i in 0 ..< s.len: s[i] = op(s[i])
  405. proc apply*[T](s: openArray[T], op: proc (x: T) {.closure.}) {.inline, since: (1, 3), effectsOf: op.} =
  406. ## Same as `apply` but for a proc that does not return anything
  407. ## and does not mutate `s` directly.
  408. runnableExamples:
  409. var message: string
  410. apply([0, 1, 2, 3, 4], proc(item: int) = message.addInt item)
  411. assert message == "01234"
  412. for i in 0 ..< s.len: op(s[i])
  413. iterator filter*[T](s: openArray[T], pred: proc(x: T): bool {.closure.}): T {.effectsOf: pred.} =
  414. ## Iterates through a container `s` and yields every item that fulfills the
  415. ## predicate `pred` (a function that returns a `bool`).
  416. ##
  417. ## Instead of using `map` and `filter`, consider using the `collect` macro
  418. ## from the `sugar` module.
  419. ##
  420. ## **See also:**
  421. ## * `sugar.collect macro<sugar.html#collect.m%2Cuntyped%2Cuntyped>`_
  422. ## * `filter proc<#filter,openArray[T],proc(T)>`_
  423. ## * `filterIt template<#filterIt.t,untyped,untyped>`_
  424. ##
  425. runnableExamples:
  426. let numbers = @[1, 4, 5, 8, 9, 7, 4]
  427. var evens = newSeq[int]()
  428. for n in filter(numbers, proc (x: int): bool = x mod 2 == 0):
  429. evens.add(n)
  430. assert evens == @[4, 8, 4]
  431. for i in 0 ..< s.len:
  432. if pred(s[i]):
  433. yield s[i]
  434. proc filter*[T](s: openArray[T], pred: proc(x: T): bool {.closure.}): seq[T]
  435. {.inline, effectsOf: pred.} =
  436. ## Returns a new sequence with all the items of `s` that fulfill the
  437. ## predicate `pred` (a function that returns a `bool`).
  438. ##
  439. ## Instead of using `map` and `filter`, consider using the `collect` macro
  440. ## from the `sugar` module.
  441. ##
  442. ## **See also:**
  443. ## * `sugar.collect macro<sugar.html#collect.m%2Cuntyped%2Cuntyped>`_
  444. ## * `filterIt template<#filterIt.t,untyped,untyped>`_
  445. ## * `filter iterator<#filter.i,openArray[T],proc(T)>`_
  446. ## * `keepIf proc<#keepIf,seq[T],proc(T)>`_ for the in-place version
  447. ##
  448. runnableExamples:
  449. let
  450. colors = @["red", "yellow", "black"]
  451. f1 = filter(colors, proc(x: string): bool = x.len < 6)
  452. f2 = filter(colors, proc(x: string): bool = x.contains('y'))
  453. assert f1 == @["red", "black"]
  454. assert f2 == @["yellow"]
  455. result = newSeq[T]()
  456. for i in 0 ..< s.len:
  457. if pred(s[i]):
  458. result.add(s[i])
  459. proc keepIf*[T](s: var seq[T], pred: proc(x: T): bool {.closure.})
  460. {.inline, effectsOf: pred.} =
  461. ## Keeps the items in the passed sequence `s` if they fulfill the
  462. ## predicate `pred` (a function that returns a `bool`).
  463. ##
  464. ## Note that `s` must be declared as a `var`.
  465. ##
  466. ## Similar to the `filter proc<#filter,openArray[T],proc(T)>`_,
  467. ## but modifies the sequence directly.
  468. ##
  469. ## **See also:**
  470. ## * `keepItIf template<#keepItIf.t,seq,untyped>`_
  471. ## * `filter proc<#filter,openArray[T],proc(T)>`_
  472. ##
  473. runnableExamples:
  474. var floats = @[13.0, 12.5, 5.8, 2.0, 6.1, 9.9, 10.1]
  475. keepIf(floats, proc(x: float): bool = x > 10)
  476. assert floats == @[13.0, 12.5, 10.1]
  477. var pos = 0
  478. for i in 0 ..< len(s):
  479. if pred(s[i]):
  480. if pos != i:
  481. when defined(gcDestructors):
  482. s[pos] = move(s[i])
  483. else:
  484. shallowCopy(s[pos], s[i])
  485. inc(pos)
  486. setLen(s, pos)
  487. func delete*[T](s: var seq[T]; slice: Slice[int]) =
  488. ## Deletes the items `s[slice]`, raising `IndexDefect` if the slice contains
  489. ## elements out of range.
  490. ##
  491. ## This operation moves all elements after `s[slice]` in linear time.
  492. runnableExamples:
  493. var a = @[10, 11, 12, 13, 14]
  494. doAssertRaises(IndexDefect): a.delete(4..5)
  495. assert a == @[10, 11, 12, 13, 14]
  496. a.delete(4..4)
  497. assert a == @[10, 11, 12, 13]
  498. a.delete(1..2)
  499. assert a == @[10, 13]
  500. a.delete(1..<1) # empty slice
  501. assert a == @[10, 13]
  502. when compileOption("boundChecks"):
  503. if not (slice.a < s.len and slice.a >= 0 and slice.b < s.len):
  504. raise newException(IndexDefect, $(slice: slice, len: s.len))
  505. if slice.b >= slice.a:
  506. template defaultImpl =
  507. var i = slice.a
  508. var j = slice.b + 1
  509. var newLen = s.len - j + i
  510. while i < newLen:
  511. when defined(gcDestructors):
  512. s[i] = move(s[j])
  513. else:
  514. s[i].shallowCopy(s[j])
  515. inc(i)
  516. inc(j)
  517. setLen(s, newLen)
  518. when nimvm: defaultImpl()
  519. else:
  520. when defined(js):
  521. let n = slice.b - slice.a + 1
  522. let first = slice.a
  523. {.emit: "`s`.splice(`first`, `n`);".}
  524. else:
  525. defaultImpl()
  526. func delete*[T](s: var seq[T]; first, last: Natural) {.deprecated: "use `delete(s, first..last)`".} =
  527. ## Deletes the items of a sequence `s` at positions `first..last`
  528. ## (including both ends of the range).
  529. ## This modifies `s` itself, it does not return a copy.
  530. runnableExamples("--warning:deprecated:off"):
  531. let outcome = @[1, 1, 1, 1, 1, 1, 1, 1]
  532. var dest = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1]
  533. dest.delete(3, 8)
  534. assert outcome == dest
  535. doAssert first <= last
  536. if first >= s.len:
  537. return
  538. var i = first
  539. var j = min(len(s), last + 1)
  540. var newLen = len(s) - j + i
  541. while i < newLen:
  542. when defined(gcDestructors):
  543. s[i] = move(s[j])
  544. else:
  545. s[i].shallowCopy(s[j])
  546. inc(i)
  547. inc(j)
  548. setLen(s, newLen)
  549. func insert*[T](dest: var seq[T], src: openArray[T], pos = 0) =
  550. ## Inserts items from `src` into `dest` at position `pos`. This modifies
  551. ## `dest` itself, it does not return a copy.
  552. ##
  553. ## Note that the elements of `src` and `dest` must be of the same type.
  554. ##
  555. runnableExamples:
  556. var dest = @[1, 1, 1, 1, 1, 1, 1, 1]
  557. let
  558. src = @[2, 2, 2, 2, 2, 2]
  559. outcome = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1]
  560. dest.insert(src, 3)
  561. assert dest == outcome
  562. var j = len(dest) - 1
  563. var i = j + len(src)
  564. if i == j: return
  565. dest.setLen(i + 1)
  566. # Move items after `pos` to the end of the sequence.
  567. while j >= pos:
  568. when defined(gcDestructors):
  569. dest[i] = move(dest[j])
  570. else:
  571. dest[i].shallowCopy(dest[j])
  572. dec(i)
  573. dec(j)
  574. # Insert items from `dest` into `dest` at `pos`
  575. inc(j)
  576. for item in src:
  577. dest[j] = item
  578. inc(j)
  579. template filterIt*(s, pred: untyped): untyped =
  580. ## Returns a new sequence with all the items of `s` that fulfill the
  581. ## predicate `pred`.
  582. ##
  583. ## Unlike the `filter proc<#filter,openArray[T],proc(T)>`_ and
  584. ## `filter iterator<#filter.i,openArray[T],proc(T)>`_,
  585. ## the predicate needs to be an expression using the `it` variable
  586. ## for testing, like: `filterIt("abcxyz", it == 'x')`.
  587. ##
  588. ## Instead of using `mapIt` and `filterIt`, consider using the `collect` macro
  589. ## from the `sugar` module.
  590. ##
  591. ## **See also:**
  592. ## * `sugar.collect macro<sugar.html#collect.m%2Cuntyped%2Cuntyped>`_
  593. ## * `filter proc<#filter,openArray[T],proc(T)>`_
  594. ## * `filter iterator<#filter.i,openArray[T],proc(T)>`_
  595. ##
  596. runnableExamples:
  597. let
  598. temperatures = @[-272.15, -2.0, 24.5, 44.31, 99.9, -113.44]
  599. acceptable = temperatures.filterIt(it < 50 and it > -10)
  600. notAcceptable = temperatures.filterIt(it > 50 or it < -10)
  601. assert acceptable == @[-2.0, 24.5, 44.31]
  602. assert notAcceptable == @[-272.15, 99.9, -113.44]
  603. var result = newSeq[typeof(s[0])]()
  604. for it {.inject.} in items(s):
  605. if pred: result.add(it)
  606. result
  607. template keepItIf*(varSeq: seq, pred: untyped) =
  608. ## Keeps the items in the passed sequence (must be declared as a `var`)
  609. ## if they fulfill the predicate.
  610. ##
  611. ## Unlike the `keepIf proc<#keepIf,seq[T],proc(T)>`_,
  612. ## the predicate needs to be an expression using
  613. ## the `it` variable for testing, like: `keepItIf("abcxyz", it == 'x')`.
  614. ##
  615. ## **See also:**
  616. ## * `keepIf proc<#keepIf,seq[T],proc(T)>`_
  617. ## * `filterIt template<#filterIt.t,untyped,untyped>`_
  618. ##
  619. runnableExamples:
  620. var candidates = @["foo", "bar", "baz", "foobar"]
  621. candidates.keepItIf(it.len == 3 and it[0] == 'b')
  622. assert candidates == @["bar", "baz"]
  623. var pos = 0
  624. for i in 0 ..< len(varSeq):
  625. let it {.inject.} = varSeq[i]
  626. if pred:
  627. if pos != i:
  628. when defined(gcDestructors):
  629. varSeq[pos] = move(varSeq[i])
  630. else:
  631. shallowCopy(varSeq[pos], varSeq[i])
  632. inc(pos)
  633. setLen(varSeq, pos)
  634. since (1, 1):
  635. template countIt*(s, pred: untyped): int =
  636. ## Returns a count of all the items that fulfill the predicate.
  637. ##
  638. ## The predicate needs to be an expression using
  639. ## the `it` variable for testing, like: `countIt(@[1, 2, 3], it > 2)`.
  640. ##
  641. runnableExamples:
  642. let numbers = @[-3, -2, -1, 0, 1, 2, 3, 4, 5, 6]
  643. iterator iota(n: int): int =
  644. for i in 0..<n: yield i
  645. assert numbers.countIt(it < 0) == 3
  646. assert countIt(iota(10), it < 2) == 2
  647. var result = 0
  648. for it {.inject.} in s:
  649. if pred: result += 1
  650. result
  651. proc all*[T](s: openArray[T], pred: proc(x: T): bool {.closure.}): bool {.effectsOf: pred.} =
  652. ## Iterates through a container and checks if every item fulfills the
  653. ## predicate.
  654. ##
  655. ## **See also:**
  656. ## * `allIt template<#allIt.t,untyped,untyped>`_
  657. ## * `any proc<#any,openArray[T],proc(T)>`_
  658. ##
  659. runnableExamples:
  660. let numbers = @[1, 4, 5, 8, 9, 7, 4]
  661. assert all(numbers, proc (x: int): bool = x < 10) == true
  662. assert all(numbers, proc (x: int): bool = x < 9) == false
  663. for i in s:
  664. if not pred(i):
  665. return false
  666. true
  667. template allIt*(s, pred: untyped): bool =
  668. ## Iterates through a container and checks if every item fulfills the
  669. ## predicate.
  670. ##
  671. ## Unlike the `all proc<#all,openArray[T],proc(T)>`_,
  672. ## the predicate needs to be an expression using
  673. ## the `it` variable for testing, like: `allIt("abba", it == 'a')`.
  674. ##
  675. ## **See also:**
  676. ## * `all proc<#all,openArray[T],proc(T)>`_
  677. ## * `anyIt template<#anyIt.t,untyped,untyped>`_
  678. ##
  679. runnableExamples:
  680. let numbers = @[1, 4, 5, 8, 9, 7, 4]
  681. assert numbers.allIt(it < 10) == true
  682. assert numbers.allIt(it < 9) == false
  683. var result = true
  684. for it {.inject.} in items(s):
  685. if not pred:
  686. result = false
  687. break
  688. result
  689. proc any*[T](s: openArray[T], pred: proc(x: T): bool {.closure.}): bool {.effectsOf: pred.} =
  690. ## Iterates through a container and checks if at least one item
  691. ## fulfills the predicate.
  692. ##
  693. ## **See also:**
  694. ## * `anyIt template<#anyIt.t,untyped,untyped>`_
  695. ## * `all proc<#all,openArray[T],proc(T)>`_
  696. ##
  697. runnableExamples:
  698. let numbers = @[1, 4, 5, 8, 9, 7, 4]
  699. assert any(numbers, proc (x: int): bool = x > 8) == true
  700. assert any(numbers, proc (x: int): bool = x > 9) == false
  701. for i in s:
  702. if pred(i):
  703. return true
  704. false
  705. template anyIt*(s, pred: untyped): bool =
  706. ## Iterates through a container and checks if at least one item
  707. ## fulfills the predicate.
  708. ##
  709. ## Unlike the `any proc<#any,openArray[T],proc(T)>`_,
  710. ## the predicate needs to be an expression using
  711. ## the `it` variable for testing, like: `anyIt("abba", it == 'a')`.
  712. ##
  713. ## **See also:**
  714. ## * `any proc<#any,openArray[T],proc(T)>`_
  715. ## * `allIt template<#allIt.t,untyped,untyped>`_
  716. ##
  717. runnableExamples:
  718. let numbers = @[1, 4, 5, 8, 9, 7, 4]
  719. assert numbers.anyIt(it > 8) == true
  720. assert numbers.anyIt(it > 9) == false
  721. var result = false
  722. for it {.inject.} in items(s):
  723. if pred:
  724. result = true
  725. break
  726. result
  727. template toSeq1(s: not iterator): untyped =
  728. # overload for typed but not iterator
  729. type OutType = typeof(items(s))
  730. when compiles(s.len):
  731. block:
  732. evalOnceAs(s2, s, compiles((let _ = s)))
  733. var i = 0
  734. var result = newSeq[OutType](s2.len)
  735. for it in s2:
  736. result[i] = it
  737. i += 1
  738. result
  739. else:
  740. var result: seq[OutType]# = @[]
  741. for it in s:
  742. result.add(it)
  743. result
  744. template toSeq2(iter: iterator): untyped =
  745. # overload for iterator
  746. evalOnceAs(iter2, iter(), false)
  747. when compiles(iter2.len):
  748. var i = 0
  749. var result = newSeq[typeof(iter2)](iter2.len)
  750. for x in iter2:
  751. result[i] = x
  752. inc i
  753. result
  754. else:
  755. type OutType = typeof(iter2())
  756. var result: seq[OutType]# = @[]
  757. when compiles(iter2()):
  758. evalOnceAs(iter4, iter, false)
  759. let iter3 = iter4()
  760. for x in iter3():
  761. result.add(x)
  762. else:
  763. for x in iter2():
  764. result.add(x)
  765. result
  766. template toSeq*(iter: untyped): untyped =
  767. ## Transforms any iterable (anything that can be iterated over, e.g. with
  768. ## a for-loop) into a sequence.
  769. ##
  770. runnableExamples:
  771. let
  772. myRange = 1..5
  773. mySet: set[int8] = {5'i8, 3, 1}
  774. assert typeof(myRange) is HSlice[system.int, system.int]
  775. assert typeof(mySet) is set[int8]
  776. let
  777. mySeq1 = toSeq(myRange)
  778. mySeq2 = toSeq(mySet)
  779. assert mySeq1 == @[1, 2, 3, 4, 5]
  780. assert mySeq2 == @[1'i8, 3, 5]
  781. when compiles(toSeq1(iter)):
  782. toSeq1(iter)
  783. elif compiles(toSeq2(iter)):
  784. toSeq2(iter)
  785. else:
  786. # overload for untyped, e.g.: `toSeq(myInlineIterator(3))`
  787. when compiles(iter.len):
  788. block:
  789. evalOnceAs(iter2, iter, true)
  790. var result = newSeq[typeof(iter)](iter2.len)
  791. var i = 0
  792. for x in iter2:
  793. result[i] = x
  794. inc i
  795. result
  796. else:
  797. var result: seq[typeof(iter)] = @[]
  798. for x in iter:
  799. result.add(x)
  800. result
  801. template foldl*(sequence, operation: untyped): untyped =
  802. ## Template to fold a sequence from left to right, returning the accumulation.
  803. ##
  804. ## The sequence is required to have at least a single element. Debug versions
  805. ## of your program will assert in this situation but release versions will
  806. ## happily go ahead. If the sequence has a single element it will be returned
  807. ## without applying `operation`.
  808. ##
  809. ## The `operation` parameter should be an expression which uses the
  810. ## variables `a` and `b` for each step of the fold. Since this is a left
  811. ## fold, for non associative binary operations like subtraction think that
  812. ## the sequence of numbers 1, 2 and 3 will be parenthesized as (((1) - 2) -
  813. ## 3).
  814. ##
  815. ## **See also:**
  816. ## * `foldl template<#foldl.t,,,>`_ with a starting parameter
  817. ## * `foldr template<#foldr.t,untyped,untyped>`_
  818. ##
  819. runnableExamples:
  820. let
  821. numbers = @[5, 9, 11]
  822. addition = foldl(numbers, a + b)
  823. subtraction = foldl(numbers, a - b)
  824. multiplication = foldl(numbers, a * b)
  825. words = @["nim", "is", "cool"]
  826. concatenation = foldl(words, a & b)
  827. procs = @["proc", "Is", "Also", "Fine"]
  828. func foo(acc, cur: string): string =
  829. result = acc & cur
  830. assert addition == 25, "Addition is (((5)+9)+11)"
  831. assert subtraction == -15, "Subtraction is (((5)-9)-11)"
  832. assert multiplication == 495, "Multiplication is (((5)*9)*11)"
  833. assert concatenation == "nimiscool"
  834. assert foldl(procs, foo(a, b)) == "procIsAlsoFine"
  835. let s = sequence
  836. assert s.len > 0, "Can't fold empty sequences"
  837. var result: typeof(s[0])
  838. result = s[0]
  839. for i in 1..<s.len:
  840. let
  841. a {.inject.} = result
  842. b {.inject.} = s[i]
  843. result = operation
  844. result
  845. template foldl*(sequence, operation, first): untyped =
  846. ## Template to fold a sequence from left to right, returning the accumulation.
  847. ##
  848. ## This version of `foldl` gets a **starting parameter**. This makes it possible
  849. ## to accumulate the sequence into a different type than the sequence elements.
  850. ##
  851. ## The `operation` parameter should be an expression which uses the variables
  852. ## `a` and `b` for each step of the fold. The `first` parameter is the
  853. ## start value (the first `a`) and therefore defines the type of the result.
  854. ##
  855. ## **See also:**
  856. ## * `foldr template<#foldr.t,untyped,untyped>`_
  857. ##
  858. runnableExamples:
  859. let
  860. numbers = @[0, 8, 1, 5]
  861. digits = foldl(numbers, a & (chr(b + ord('0'))), "")
  862. assert digits == "0815"
  863. var result: typeof(first) = first
  864. for x in items(sequence):
  865. let
  866. a {.inject.} = result
  867. b {.inject.} = x
  868. result = operation
  869. result
  870. template foldr*(sequence, operation: untyped): untyped =
  871. ## Template to fold a sequence from right to left, returning the accumulation.
  872. ##
  873. ## The sequence is required to have at least a single element. Debug versions
  874. ## of your program will assert in this situation but release versions will
  875. ## happily go ahead. If the sequence has a single element it will be returned
  876. ## without applying `operation`.
  877. ##
  878. ## The `operation` parameter should be an expression which uses the
  879. ## variables `a` and `b` for each step of the fold. Since this is a right
  880. ## fold, for non associative binary operations like subtraction think that
  881. ## the sequence of numbers 1, 2 and 3 will be parenthesized as (1 - (2 -
  882. ## (3))).
  883. ##
  884. ## **See also:**
  885. ## * `foldl template<#foldl.t,untyped,untyped>`_
  886. ## * `foldl template<#foldl.t,,,>`_ with a starting parameter
  887. ##
  888. runnableExamples:
  889. let
  890. numbers = @[5, 9, 11]
  891. addition = foldr(numbers, a + b)
  892. subtraction = foldr(numbers, a - b)
  893. multiplication = foldr(numbers, a * b)
  894. words = @["nim", "is", "cool"]
  895. concatenation = foldr(words, a & b)
  896. assert addition == 25, "Addition is (5+(9+(11)))"
  897. assert subtraction == 7, "Subtraction is (5-(9-(11)))"
  898. assert multiplication == 495, "Multiplication is (5*(9*(11)))"
  899. assert concatenation == "nimiscool"
  900. let s = sequence # xxx inefficient, use {.evalonce.} pending #13750
  901. let n = s.len
  902. assert n > 0, "Can't fold empty sequences"
  903. var result = s[n - 1]
  904. for i in countdown(n - 2, 0):
  905. let
  906. a {.inject.} = s[i]
  907. b {.inject.} = result
  908. result = operation
  909. result
  910. template mapIt*(s: typed, op: untyped): untyped =
  911. ## Returns a new sequence with the results of the `op` proc applied to every
  912. ## item in the container `s`.
  913. ##
  914. ## Since the input is not modified you can use it to
  915. ## transform the type of the elements in the input container.
  916. ##
  917. ## The template injects the `it` variable which you can use directly in an
  918. ## expression.
  919. ##
  920. ## Instead of using `mapIt` and `filterIt`, consider using the `collect` macro
  921. ## from the `sugar` module.
  922. ##
  923. ## **See also:**
  924. ## * `sugar.collect macro<sugar.html#collect.m%2Cuntyped%2Cuntyped>`_
  925. ## * `map proc<#map,openArray[T],proc(T)>`_
  926. ## * `applyIt template<#applyIt.t,untyped,untyped>`_ for the in-place version
  927. ##
  928. runnableExamples:
  929. let
  930. nums = @[1, 2, 3, 4]
  931. strings = nums.mapIt($(4 * it))
  932. assert strings == @["4", "8", "12", "16"]
  933. type OutType = typeof((
  934. block:
  935. var it{.inject.}: typeof(items(s), typeOfIter);
  936. op), typeOfProc)
  937. when OutType is not (proc):
  938. # Here, we avoid to create closures in loops.
  939. # This avoids https://github.com/nim-lang/Nim/issues/12625
  940. when compiles(s.len):
  941. block: # using a block avoids https://github.com/nim-lang/Nim/issues/8580
  942. # BUG: `evalOnceAs(s2, s, false)` would lead to C compile errors
  943. # (`error: use of undeclared identifier`) instead of Nim compile errors
  944. evalOnceAs(s2, s, compiles((let _ = s)))
  945. var i = 0
  946. var result = newSeq[OutType](s2.len)
  947. for it {.inject.} in s2:
  948. result[i] = op
  949. i += 1
  950. result
  951. else:
  952. var result: seq[OutType]# = @[]
  953. # use `items` to avoid https://github.com/nim-lang/Nim/issues/12639
  954. for it {.inject.} in items(s):
  955. result.add(op)
  956. result
  957. else:
  958. # `op` is going to create closures in loops, let's fallback to `map`.
  959. # NOTE: Without this fallback, developers have to define a helper function and
  960. # call `map`:
  961. # [1, 2].map((it) => ((x: int) => it + x))
  962. # With this fallback, above code can be simplified to:
  963. # [1, 2].mapIt((x: int) => it + x)
  964. # In this case, `mapIt` is just syntax sugar for `map`.
  965. type InType = typeof(items(s), typeOfIter)
  966. # Use a help proc `f` to create closures for each element in `s`
  967. let f = proc (x: InType): OutType =
  968. let it {.inject.} = x
  969. op
  970. map(s, f)
  971. template applyIt*(varSeq, op: untyped) =
  972. ## Convenience template around the mutable `apply` proc to reduce typing.
  973. ##
  974. ## The template injects the `it` variable which you can use directly in an
  975. ## expression. The expression has to return the same type as the elements
  976. ## of the sequence you are mutating.
  977. ##
  978. ## **See also:**
  979. ## * `apply proc<#apply,openArray[T],proc(T)_2>`_
  980. ## * `mapIt template<#mapIt.t,typed,untyped>`_
  981. ##
  982. runnableExamples:
  983. var nums = @[1, 2, 3, 4]
  984. nums.applyIt(it * 3)
  985. assert nums[0] + nums[3] == 15
  986. for i in low(varSeq) .. high(varSeq):
  987. let it {.inject.} = varSeq[i]
  988. varSeq[i] = op
  989. template newSeqWith*(len: int, init: untyped): untyped =
  990. ## Creates a new `seq` of length `len`, calling `init` to initialize
  991. ## each value of the seq.
  992. ##
  993. ## Useful for creating "2D" seqs - seqs containing other seqs
  994. ## or to populate fields of the created seq.
  995. runnableExamples:
  996. ## Creates a seq containing 5 bool seqs, each of length of 3.
  997. var seq2D = newSeqWith(5, newSeq[bool](3))
  998. assert seq2D.len == 5
  999. assert seq2D[0].len == 3
  1000. assert seq2D[4][2] == false
  1001. ## Creates a seq with random numbers
  1002. import std/random
  1003. var seqRand = newSeqWith(20, rand(1.0))
  1004. assert seqRand[0] != seqRand[1]
  1005. type T = typeof(init)
  1006. let newLen = len
  1007. when supportsCopyMem(T) and declared(newSeqUninit):
  1008. var result = newSeqUninit[T](newLen)
  1009. else: # TODO: use `newSeqUnsafe` when that's available
  1010. var result = newSeq[T](newLen)
  1011. for i in 0 ..< newLen:
  1012. result[i] = init
  1013. move(result) # refs bug #7295
  1014. func mapLitsImpl(constructor: NimNode; op: NimNode; nested: bool;
  1015. filter = nnkLiterals): NimNode =
  1016. if constructor.kind in filter:
  1017. result = newNimNode(nnkCall, lineInfoFrom = constructor)
  1018. result.add op
  1019. result.add constructor
  1020. else:
  1021. result = copyNimNode(constructor)
  1022. for v in constructor:
  1023. if nested or v.kind in filter:
  1024. result.add mapLitsImpl(v, op, nested, filter)
  1025. else:
  1026. result.add v
  1027. macro mapLiterals*(constructor, op: untyped;
  1028. nested = true): untyped =
  1029. ## Applies `op` to each of the **atomic** literals like `3`
  1030. ## or `"abc"` in the specified `constructor` AST. This can
  1031. ## be used to map every array element to some target type:
  1032. runnableExamples:
  1033. let x = mapLiterals([0.1, 1.2, 2.3, 3.4], int)
  1034. doAssert x is array[4, int]
  1035. doAssert x == [int(0.1), int(1.2), int(2.3), int(3.4)]
  1036. ## If `nested` is true (which is the default), the literals are replaced
  1037. ## everywhere in the `constructor` AST, otherwise only the first level
  1038. ## is considered:
  1039. runnableExamples:
  1040. let a = mapLiterals((1.2, (2.3, 3.4), 4.8), int)
  1041. let b = mapLiterals((1.2, (2.3, 3.4), 4.8), int, nested=false)
  1042. assert a == (1, (2, 3), 4)
  1043. assert b == (1, (2.3, 3.4), 4)
  1044. let c = mapLiterals((1, (2, 3), 4, (5, 6)), `$`)
  1045. let d = mapLiterals((1, (2, 3), 4, (5, 6)), `$`, nested=false)
  1046. assert c == ("1", ("2", "3"), "4", ("5", "6"))
  1047. assert d == ("1", (2, 3), "4", (5, 6))
  1048. ## There are no constraints for the `constructor` AST, it
  1049. ## works for nested tuples of arrays of sets etc.
  1050. result = mapLitsImpl(constructor, op, nested.boolVal)
  1051. iterator items*[T](xs: iterator: T): T =
  1052. ## Iterates over each element yielded by a closure iterator. This may
  1053. ## not seem particularly useful on its own, but this allows closure
  1054. ## iterators to be used by the mapIt, filterIt, allIt, anyIt, etc.
  1055. ## templates.
  1056. for x in xs():
  1057. yield x