sequtils.nim 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404
  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 `seq`:idx: type, but for three built-in container types under
  11. ## 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. ## * pass `anonymous proc<manual.html#procedures-anonymous-procs>`_
  30. ## * import `sugar module<sugar.html>`_ and use
  31. ## `=> macro<sugar.html#%3D>.m,untyped,untyped>`_
  32. ## * use `...It templates<#18>`_
  33. ## (`mapIt<#mapIt.t,typed,untyped>`_,
  34. ## `filterIt<#filterIt.t,untyped,untyped>`_, etc.)
  35. ##
  36. ## The chaining of functions is possible thanks to the
  37. ## `method call syntax<manual.html#procedures-method-call-syntax>`_.
  38. ##
  39. ## .. code-block::
  40. ## import sequtils, sugar
  41. ##
  42. ## # Creating a sequence from 1 to 10, multiplying each member by 2,
  43. ## # keeping only the members which are not divisible by 6.
  44. ## let
  45. ## foo = toSeq(1..10).map(x => x*2).filter(x => x mod 6 != 0)
  46. ## bar = toSeq(1..10).mapIt(it*2).filterIt(it mod 6 != 0)
  47. ##
  48. ## doAssert foo == bar
  49. ## echo foo # @[2, 4, 8, 10, 14, 16, 20]
  50. ##
  51. ## echo foo.any(x => x > 17) # true
  52. ## echo bar.allIt(it < 20) # false
  53. ## echo foo.foldl(a + b) # 74; sum of all members
  54. ##
  55. ## .. code-block::
  56. ## import sequtils
  57. ## from strutils import join
  58. ##
  59. ## let
  60. ## vowels = @"aeiou" # creates a sequence @['a', 'e', 'i', 'o', 'u']
  61. ## foo = "sequtils is an awesome module"
  62. ##
  63. ## echo foo.filterIt(it notin vowels).join # "sqtls s n wsm mdl"
  64. ##
  65. ## ----
  66. ##
  67. ## **See also**:
  68. ## * `strutils module<strutils.html>`_ for common string functions
  69. ## * `sugar module<sugar.html>`_ for syntactic sugar macros
  70. ## * `algorithm module<algorithm.html>`_ for common generic algorithms
  71. ## * `json module<json.html>`_ for a structure which allows
  72. ## heterogeneous members
  73. include "system/inclrtl"
  74. import macros
  75. when not defined(nimhygiene):
  76. {.pragma: dirty.}
  77. macro evalOnceAs(expAlias, exp: untyped,
  78. letAssigneable: static[bool]): untyped =
  79. ## Injects ``expAlias`` in caller scope, to avoid bugs involving multiple
  80. ## substitution in macro arguments such as
  81. ## https://github.com/nim-lang/Nim/issues/7187
  82. ## ``evalOnceAs(myAlias, myExp)`` will behave as ``let myAlias = myExp``
  83. ## except when ``letAssigneable`` is false (e.g. to handle openArray) where
  84. ## it just forwards ``exp`` unchanged
  85. expectKind(expAlias, nnkIdent)
  86. var val = exp
  87. result = newStmtList()
  88. # If `exp` is not a symbol we evaluate it once here and then use the temporary
  89. # symbol as alias
  90. if exp.kind != nnkSym and letAssigneable:
  91. val = genSym()
  92. result.add(newLetStmt(val, exp))
  93. result.add(
  94. newProc(name = genSym(nskTemplate, $expAlias), params = [getType(untyped)],
  95. body = val, procType = nnkTemplateDef))
  96. proc concat*[T](seqs: varargs[seq[T]]): seq[T] =
  97. ## Takes several sequences' items and returns them inside a new sequence.
  98. ## All sequences must be of the same type.
  99. ##
  100. ## See also:
  101. ## * `distribute proc<#distribute,seq[T],Positive>`_ for a reverse
  102. ## operation
  103. ##
  104. runnableExamples:
  105. let
  106. s1 = @[1, 2, 3]
  107. s2 = @[4, 5]
  108. s3 = @[6, 7]
  109. total = concat(s1, s2, s3)
  110. assert total == @[1, 2, 3, 4, 5, 6, 7]
  111. var L = 0
  112. for seqitm in items(seqs): inc(L, len(seqitm))
  113. newSeq(result, L)
  114. var i = 0
  115. for s in items(seqs):
  116. for itm in items(s):
  117. result[i] = itm
  118. inc(i)
  119. proc count*[T](s: openArray[T], x: T): int =
  120. ## Returns the number of occurrences of the item `x` in the container `s`.
  121. ##
  122. runnableExamples:
  123. let
  124. a = @[1, 2, 2, 3, 2, 4, 2]
  125. b = "abracadabra"
  126. assert count(a, 2) == 4
  127. assert count(a, 99) == 0
  128. assert count(b, 'r') == 2
  129. for itm in items(s):
  130. if itm == x:
  131. inc result
  132. proc cycle*[T](s: openArray[T], n: Natural): seq[T] =
  133. ## Returns a new sequence with the items of the container `s` repeated
  134. ## `n` times.
  135. ## `n` must be a non-negative number (zero or more).
  136. ##
  137. runnableExamples:
  138. let
  139. s = @[1, 2, 3]
  140. total = s.cycle(3)
  141. assert total == @[1, 2, 3, 1, 2, 3, 1, 2, 3]
  142. result = newSeq[T](n * s.len)
  143. var o = 0
  144. for x in 0 ..< n:
  145. for e in s:
  146. result[o] = e
  147. inc o
  148. proc repeat*[T](x: T, n: Natural): seq[T] =
  149. ## Returns a new sequence with the item `x` repeated `n` times.
  150. ## `n` must be a non-negative number (zero or more).
  151. ##
  152. runnableExamples:
  153. let
  154. total = repeat(5, 3)
  155. assert total == @[5, 5, 5]
  156. result = newSeq[T](n)
  157. for i in 0 ..< n:
  158. result[i] = x
  159. proc deduplicate*[T](s: openArray[T], isSorted: bool = false): seq[T] =
  160. ## Returns a new sequence without duplicates.
  161. ##
  162. ## Setting the optional argument ``isSorted`` to ``true`` (default: false)
  163. ## uses a faster algorithm for deduplication.
  164. ##
  165. runnableExamples:
  166. let
  167. dup1 = @[1, 1, 3, 4, 2, 2, 8, 1, 4]
  168. dup2 = @["a", "a", "c", "d", "d"]
  169. unique1 = deduplicate(dup1)
  170. unique2 = deduplicate(dup2, isSorted = true)
  171. assert unique1 == @[1, 3, 4, 2, 8]
  172. assert unique2 == @["a", "c", "d"]
  173. result = @[]
  174. if s.len > 0:
  175. if isSorted:
  176. var prev = s[0]
  177. result.add(prev)
  178. for i in 1..s.high:
  179. if s[i] != prev:
  180. prev = s[i]
  181. result.add(prev)
  182. else:
  183. for itm in items(s):
  184. if not result.contains(itm): result.add(itm)
  185. proc zip*[S, T](s1: openArray[S], s2: openArray[T]): seq[tuple[a: S, b: T]] =
  186. ## Returns a new sequence with a combination of the two input containers.
  187. ##
  188. ## The input containers can be of different types.
  189. ## If one container is shorter, the remaining items in the longer container
  190. ## are discarded.
  191. ##
  192. ## For convenience you can access the returned tuples through the named
  193. ## fields `a` and `b`.
  194. ##
  195. runnableExamples:
  196. let
  197. short = @[1, 2, 3]
  198. long = @[6, 5, 4, 3, 2, 1]
  199. words = @["one", "two", "three"]
  200. letters = "abcd"
  201. zip1 = zip(short, long)
  202. zip2 = zip(short, words)
  203. zip3 = zip(long, letters)
  204. assert zip1 == @[(1, 6), (2, 5), (3, 4)]
  205. assert zip2 == @[(1, "one"), (2, "two"), (3, "three")]
  206. assert zip3 == @[(a: 6, b: 'a'), (a: 5, b: 'b'), (a: 4, b: 'c'),
  207. (a: 3, b: 'd')]
  208. assert zip1[2].b == 4
  209. assert zip2[2].b == "three"
  210. var m = min(s1.len, s2.len)
  211. newSeq(result, m)
  212. for i in 0 ..< m:
  213. result[i] = (s1[i], s2[i])
  214. proc distribute*[T](s: seq[T], num: Positive, spread = true): seq[seq[T]] =
  215. ## Splits and distributes a sequence `s` into `num` sub-sequences.
  216. ##
  217. ## Returns a sequence of `num` sequences. For *some* input values this is the
  218. ## inverse of the `concat <#concat,varargs[seq[T]]>`_ proc.
  219. ## The input sequence `s` can be empty, which will produce
  220. ## `num` empty sequences.
  221. ##
  222. ## If `spread` is false and the length of `s` is not a multiple of `num`, the
  223. ## proc will max out the first sub-sequence with ``1 + len(s) div num``
  224. ## entries, leaving the remainder of elements to the last sequence.
  225. ##
  226. ## On the other hand, if `spread` is true, the proc will distribute evenly
  227. ## the remainder of the division across all sequences, which makes the result
  228. ## more suited to multithreading where you are passing equal sized work units
  229. ## to a thread pool and want to maximize core usage.
  230. ##
  231. runnableExamples:
  232. let numbers = @[1, 2, 3, 4, 5, 6, 7]
  233. assert numbers.distribute(3) == @[@[1, 2, 3], @[4, 5], @[6, 7]]
  234. assert numbers.distribute(3, false) == @[@[1, 2, 3], @[4, 5, 6], @[7]]
  235. assert numbers.distribute(6)[0] == @[1, 2]
  236. assert numbers.distribute(6)[1] == @[3]
  237. if num < 2:
  238. result = @[s]
  239. return
  240. let num = int(num) # XXX probably only needed because of .. bug
  241. # Create the result and calculate the stride size and the remainder if any.
  242. result = newSeq[seq[T]](num)
  243. var
  244. stride = s.len div num
  245. first = 0
  246. last = 0
  247. extra = s.len mod num
  248. if extra == 0 or spread == false:
  249. # Use an algorithm which overcounts the stride and minimizes reading limits.
  250. if extra > 0: inc(stride)
  251. for i in 0 ..< num:
  252. result[i] = newSeq[T]()
  253. for g in first ..< min(s.len, first + stride):
  254. result[i].add(s[g])
  255. first += stride
  256. else:
  257. # Use an undercounting algorithm which *adds* the remainder each iteration.
  258. for i in 0 ..< num:
  259. last = first + stride
  260. if extra > 0:
  261. extra -= 1
  262. inc(last)
  263. result[i] = newSeq[T]()
  264. for g in first ..< last:
  265. result[i].add(s[g])
  266. first = last
  267. proc map*[T, S](s: openArray[T], op: proc (x: T): S {.closure.}):
  268. seq[S]{.inline.} =
  269. ## Returns a new sequence with the results of `op` proc applied to every
  270. ## item in the container `s`.
  271. ##
  272. ## Since the input is not modified you can use it to
  273. ## transform the type of the elements in the input container.
  274. ##
  275. ## See also:
  276. ## * `mapIt template<#mapIt.t,typed,untyped>`_
  277. ## * `apply proc<#apply,openArray[T],proc(T)_2>`_ for the in-place version
  278. ##
  279. runnableExamples:
  280. let
  281. a = @[1, 2, 3, 4]
  282. b = map(a, proc(x: int): string = $x)
  283. assert b == @["1", "2", "3", "4"]
  284. newSeq(result, s.len)
  285. for i in 0 ..< s.len:
  286. result[i] = op(s[i])
  287. proc apply*[T](s: var openArray[T], op: proc (x: var T) {.closure.})
  288. {.inline.} =
  289. ## Applies `op` to every item in `s` modifying it directly.
  290. ##
  291. ## Note that container `s` must be declared as a ``var``
  292. ## and it is required for your input and output types to
  293. ## be the same, since `s` is modified in-place.
  294. ## The parameter function takes a ``var T`` type parameter.
  295. ##
  296. ## See also:
  297. ## * `applyIt template<#applyIt.t,untyped,untyped>`_
  298. ## * `map proc<#map,openArray[T],proc(T)>`_
  299. ##
  300. runnableExamples:
  301. var a = @["1", "2", "3", "4"]
  302. apply(a, proc(x: var string) = x &= "42")
  303. assert a == @["142", "242", "342", "442"]
  304. for i in 0 ..< s.len: op(s[i])
  305. proc apply*[T](s: var openArray[T], op: proc (x: T): T {.closure.})
  306. {.inline.} =
  307. ## Applies `op` to every item in `s` modifying it directly.
  308. ##
  309. ## Note that container `s` must be declared as a ``var``
  310. ## and it is required for your input and output types to
  311. ## be the same, since `s` is modified in-place.
  312. ## The parameter function takes and returns a ``T`` type variable.
  313. ##
  314. ## See also:
  315. ## * `applyIt template<#applyIt.t,untyped,untyped>`_
  316. ## * `map proc<#map,openArray[T],proc(T)>`_
  317. ##
  318. runnableExamples:
  319. var a = @["1", "2", "3", "4"]
  320. apply(a, proc(x: string): string = x & "42")
  321. assert a == @["142", "242", "342", "442"]
  322. for i in 0 ..< s.len: s[i] = op(s[i])
  323. iterator filter*[T](s: openArray[T], pred: proc(x: T): bool {.closure.}): T =
  324. ## Iterates through a container `s` and yields every item that fulfills the
  325. ## predicate `pred` (function that returns a `bool`).
  326. ##
  327. ## See also:
  328. ## * `fliter proc<#filter,openArray[T],proc(T)>`_
  329. ## * `filterIt template<#filterIt.t,untyped,untyped>`_
  330. ##
  331. runnableExamples:
  332. let numbers = @[1, 4, 5, 8, 9, 7, 4]
  333. var evens = newSeq[int]()
  334. for n in filter(numbers, proc (x: int): bool = x mod 2 == 0):
  335. evens.add(n)
  336. assert evens == @[4, 8, 4]
  337. for i in 0 ..< s.len:
  338. if pred(s[i]):
  339. yield s[i]
  340. proc filter*[T](s: openArray[T], pred: proc(x: T): bool {.closure.}): seq[T]
  341. {.inline.} =
  342. ## Returns a new sequence with all the items of `s` that fulfilled the
  343. ## predicate `pred` (function that returns a `bool`).
  344. ##
  345. ## See also:
  346. ## * `filterIt template<#filterIt.t,untyped,untyped>`_
  347. ## * `filter iterator<#filter.i,openArray[T],proc(T)>`_
  348. ## * `keepIf proc<#keepIf,seq[T],proc(T)>`_ for the in-place version
  349. ##
  350. runnableExamples:
  351. let
  352. colors = @["red", "yellow", "black"]
  353. f1 = filter(colors, proc(x: string): bool = x.len < 6)
  354. f2 = filter(colors, proc(x: string): bool = x.contains('y'))
  355. assert f1 == @["red", "black"]
  356. assert f2 == @["yellow"]
  357. result = newSeq[T]()
  358. for i in 0 ..< s.len:
  359. if pred(s[i]):
  360. result.add(s[i])
  361. proc keepIf*[T](s: var seq[T], pred: proc(x: T): bool {.closure.})
  362. {.inline.} =
  363. ## Keeps the items in the passed sequence `s` if they fulfilled the
  364. ## predicate `pred` (function that returns a `bool`).
  365. ##
  366. ## Note that `s` must be declared as a ``var``.
  367. ##
  368. ## Similar to the `filter proc<#filter,openArray[T],proc(T)>`_,
  369. ## but modifies the sequence directly.
  370. ##
  371. ## See also:
  372. ## * `keepItIf template<#keepItIf.t,seq,untyped>`_
  373. ## * `filter proc<#filter,openArray[T],proc(T)>`_
  374. ##
  375. runnableExamples:
  376. var floats = @[13.0, 12.5, 5.8, 2.0, 6.1, 9.9, 10.1]
  377. keepIf(floats, proc(x: float): bool = x > 10)
  378. assert floats == @[13.0, 12.5, 10.1]
  379. var pos = 0
  380. for i in 0 ..< len(s):
  381. if pred(s[i]):
  382. if pos != i:
  383. shallowCopy(s[pos], s[i])
  384. inc(pos)
  385. setLen(s, pos)
  386. proc delete*[T](s: var seq[T]; first, last: Natural) =
  387. ## Deletes in the items of a sequence `s` at positions ``first..last``
  388. ## (including both ends of a range).
  389. ## This modifies `s` itself, it does not return a copy.
  390. ##
  391. runnableExamples:
  392. let outcome = @[1, 1, 1, 1, 1, 1, 1, 1]
  393. var dest = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1]
  394. dest.delete(3, 8)
  395. assert outcome == dest
  396. var i = first
  397. var j = min(len(s), last+1)
  398. var newLen = len(s)-j+i
  399. while i < newLen:
  400. s[i].shallowCopy(s[j])
  401. inc(i)
  402. inc(j)
  403. setLen(s, newLen)
  404. proc insert*[T](dest: var seq[T], src: openArray[T], pos = 0) =
  405. ## Inserts items from `src` into `dest` at position `pos`. This modifies
  406. ## `dest` itself, it does not return a copy.
  407. ##
  408. ## Notice that `src` and `dest` must be of the same type.
  409. ##
  410. runnableExamples:
  411. var dest = @[1, 1, 1, 1, 1, 1, 1, 1]
  412. let
  413. src = @[2, 2, 2, 2, 2, 2]
  414. outcome = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1]
  415. dest.insert(src, 3)
  416. assert dest == outcome
  417. var j = len(dest) - 1
  418. var i = len(dest) + len(src) - 1
  419. dest.setLen(i + 1)
  420. # Move items after `pos` to the end of the sequence.
  421. while j >= pos:
  422. dest[i].shallowCopy(dest[j])
  423. dec(i)
  424. dec(j)
  425. # Insert items from `dest` into `dest` at `pos`
  426. inc(j)
  427. for item in src:
  428. dest[j] = item
  429. inc(j)
  430. template filterIt*(s, pred: untyped): untyped =
  431. ## Returns a new sequence with all the items of `s` that fulfilled the
  432. ## predicate `pred`.
  433. ##
  434. ## Unlike the `filter proc<#filter,openArray[T],proc(T)>`_ and
  435. ## `filter iterator<#filter.i,openArray[T],proc(T)>`_,
  436. ## the predicate needs to be an expression using the ``it`` variable
  437. ## for testing, like: ``filterIt("abcxyz", it == 'x')``.
  438. ##
  439. ## See also:
  440. ## * `fliter proc<#filter,openArray[T],proc(T)>`_
  441. ## * `filter iterator<#filter.i,openArray[T],proc(T)>`_
  442. ##
  443. runnableExamples:
  444. let
  445. temperatures = @[-272.15, -2.0, 24.5, 44.31, 99.9, -113.44]
  446. acceptable = temperatures.filterIt(it < 50 and it > -10)
  447. notAcceptable = temperatures.filterIt(it > 50 or it < -10)
  448. assert acceptable == @[-2.0, 24.5, 44.31]
  449. assert notAcceptable == @[-272.15, 99.9, -113.44]
  450. var result = newSeq[type(s[0])]()
  451. for it {.inject.} in items(s):
  452. if pred: result.add(it)
  453. result
  454. template keepItIf*(varSeq: seq, pred: untyped) =
  455. ## Keeps the items in the passed sequence (must be declared as a ``var``)
  456. ## if they fulfilled the predicate.
  457. ##
  458. ## Unlike the `keepIf proc<#keepIf,seq[T],proc(T)>`_,
  459. ## the predicate needs to be an expression using
  460. ## the ``it`` variable for testing, like: ``keepItIf("abcxyz", it == 'x')``.
  461. ##
  462. ## See also:
  463. ## * `keepIf proc<#keepIf,seq[T],proc(T)>`_
  464. ## * `filterIt template<#filterIt.t,untyped,untyped>`_
  465. ##
  466. runnableExamples:
  467. var candidates = @["foo", "bar", "baz", "foobar"]
  468. candidates.keepItIf(it.len == 3 and it[0] == 'b')
  469. assert candidates == @["bar", "baz"]
  470. var pos = 0
  471. for i in 0 ..< len(varSeq):
  472. let it {.inject.} = varSeq[i]
  473. if pred:
  474. if pos != i:
  475. shallowCopy(varSeq[pos], varSeq[i])
  476. inc(pos)
  477. setLen(varSeq, pos)
  478. proc all*[T](s: openArray[T], pred: proc(x: T): bool {.closure.}): bool =
  479. ## Iterates through a container and checks if every item fulfills the
  480. ## predicate.
  481. ##
  482. ## See also:
  483. ## * `allIt template<#allIt.t,untyped,untyped>`_
  484. ## * `any proc<#any,openArray[T],proc(T)>`_
  485. ##
  486. runnableExamples:
  487. let numbers = @[1, 4, 5, 8, 9, 7, 4]
  488. assert all(numbers, proc (x: int): bool = return x < 10) == true
  489. assert all(numbers, proc (x: int): bool = return x < 9) == false
  490. for i in s:
  491. if not pred(i):
  492. return false
  493. return true
  494. template allIt*(s, pred: untyped): bool =
  495. ## Iterates through a container and checks if every item fulfills the
  496. ## predicate.
  497. ##
  498. ## Unlike the `all proc<#all,openArray[T],proc(T)>`_,
  499. ## the predicate needs to be an expression using
  500. ## the ``it`` variable for testing, like: ``allIt("abba", it == 'a')``.
  501. ##
  502. ## See also:
  503. ## * `all proc<#all,openArray[T],proc(T)>`_
  504. ## * `anyIt template<#anyIt.t,untyped,untyped>`_
  505. ##
  506. runnableExamples:
  507. let numbers = @[1, 4, 5, 8, 9, 7, 4]
  508. assert numbers.allIt(it < 10) == true
  509. assert numbers.allIt(it < 9) == false
  510. var result = true
  511. for it {.inject.} in items(s):
  512. if not pred:
  513. result = false
  514. break
  515. result
  516. proc any*[T](s: openArray[T], pred: proc(x: T): bool {.closure.}): bool =
  517. ## Iterates through a container and checks if some item fulfills the
  518. ## predicate.
  519. ##
  520. ## See also:
  521. ## * `anyIt template<#anyIt.t,untyped,untyped>`_
  522. ## * `all proc<#all,openArray[T],proc(T)>`_
  523. ##
  524. runnableExamples:
  525. let numbers = @[1, 4, 5, 8, 9, 7, 4]
  526. assert any(numbers, proc (x: int): bool = return x > 8) == true
  527. assert any(numbers, proc (x: int): bool = return x > 9) == false
  528. for i in s:
  529. if pred(i):
  530. return true
  531. return false
  532. template anyIt*(s, pred: untyped): bool =
  533. ## Iterates through a container and checks if some item fulfills the
  534. ## predicate.
  535. ##
  536. ## Unlike the `any proc<#any,openArray[T],proc(T)>`_,
  537. ## the predicate needs to be an expression using
  538. ## the ``it`` variable for testing, like: ``anyIt("abba", it == 'a')``.
  539. ##
  540. ## See also:
  541. ## * `any proc<#any,openArray[T],proc(T)>`_
  542. ## * `allIt template<#allIt.t,untyped,untyped>`_
  543. ##
  544. runnableExamples:
  545. let numbers = @[1, 4, 5, 8, 9, 7, 4]
  546. assert numbers.anyIt(it > 8) == true
  547. assert numbers.anyIt(it > 9) == false
  548. var result = false
  549. for it {.inject.} in items(s):
  550. if pred:
  551. result = true
  552. break
  553. result
  554. template toSeq1(s: not iterator): untyped =
  555. # overload for typed but not iterator
  556. type OutType = type(items(s))
  557. when compiles(s.len):
  558. block:
  559. evalOnceAs(s2, s, compiles((let _ = s)))
  560. var i = 0
  561. var result = newSeq[OutType](s2.len)
  562. for it in s2:
  563. result[i] = it
  564. i += 1
  565. result
  566. else:
  567. var result: seq[OutType] = @[]
  568. for it in s:
  569. result.add(it)
  570. result
  571. template toSeq2(iter: iterator): untyped =
  572. # overload for iterator
  573. evalOnceAs(iter2, iter(), false)
  574. when compiles(iter2.len):
  575. var i = 0
  576. var result = newSeq[type(iter2)](iter2.len)
  577. for x in iter2:
  578. result[i] = x
  579. inc i
  580. result
  581. else:
  582. type OutType = type(iter2())
  583. var result: seq[OutType] = @[]
  584. when compiles(iter2()):
  585. evalOnceAs(iter4, iter, false)
  586. let iter3 = iter4()
  587. for x in iter3():
  588. result.add(x)
  589. else:
  590. for x in iter2():
  591. result.add(x)
  592. result
  593. template toSeq*(iter: untyped): untyped =
  594. ## Transforms any iterable (anything that can be iterated over, e.g. with
  595. ## a for-loop) into a sequence.
  596. ##
  597. runnableExamples:
  598. let
  599. myRange = 1..5
  600. mySet: set[int8] = {5'i8, 3, 1}
  601. assert type(myRange) is HSlice[system.int, system.int]
  602. assert type(mySet) is set[int8]
  603. let
  604. mySeq1 = toSeq(myRange)
  605. mySeq2 = toSeq(mySet)
  606. assert mySeq1 == @[1, 2, 3, 4, 5]
  607. assert mySeq2 == @[1'i8, 3, 5]
  608. when compiles(toSeq1(iter)):
  609. toSeq1(iter)
  610. elif compiles(toSeq2(iter)):
  611. toSeq2(iter)
  612. else:
  613. # overload for untyped, e.g.: `toSeq(myInlineIterator(3))`
  614. when compiles(iter.len):
  615. block:
  616. evalOnceAs(iter2, iter, true)
  617. var result = newSeq[type(iter)](iter2.len)
  618. var i = 0
  619. for x in iter2:
  620. result[i] = x
  621. inc i
  622. result
  623. else:
  624. var result: seq[type(iter)] = @[]
  625. for x in iter:
  626. result.add(x)
  627. result
  628. template foldl*(sequence, operation: untyped): untyped =
  629. ## Template to fold a sequence from left to right, returning the accumulation.
  630. ##
  631. ## The sequence is required to have at least a single element. Debug versions
  632. ## of your program will assert in this situation but release versions will
  633. ## happily go ahead. If the sequence has a single element it will be returned
  634. ## without applying ``operation``.
  635. ##
  636. ## The ``operation`` parameter should be an expression which uses the
  637. ## variables ``a`` and ``b`` for each step of the fold. Since this is a left
  638. ## fold, for non associative binary operations like subtraction think that
  639. ## the sequence of numbers 1, 2 and 3 will be parenthesized as (((1) - 2) -
  640. ## 3).
  641. ##
  642. ## See also:
  643. ## * `foldl template<#foldl.t,,,>`_ with a starting parameter
  644. ## * `foldr template<#foldr.t,untyped,untyped>`_
  645. ##
  646. runnableExamples:
  647. let
  648. numbers = @[5, 9, 11]
  649. addition = foldl(numbers, a + b)
  650. subtraction = foldl(numbers, a - b)
  651. multiplication = foldl(numbers, a * b)
  652. words = @["nim", "is", "cool"]
  653. concatenation = foldl(words, a & b)
  654. assert addition == 25, "Addition is (((5)+9)+11)"
  655. assert subtraction == -15, "Subtraction is (((5)-9)-11)"
  656. assert multiplication == 495, "Multiplication is (((5)*9)*11)"
  657. assert concatenation == "nimiscool"
  658. let s = sequence
  659. assert s.len > 0, "Can't fold empty sequences"
  660. var result: type(s[0])
  661. result = s[0]
  662. for i in 1..<s.len:
  663. let
  664. a {.inject.} = result
  665. b {.inject.} = s[i]
  666. result = operation
  667. result
  668. template foldl*(sequence, operation, first): untyped =
  669. ## Template to fold a sequence from left to right, returning the accumulation.
  670. ##
  671. ## This version of ``foldl`` gets a **starting parameter**. This makes it possible
  672. ## to accumulate the sequence into a different type than the sequence elements.
  673. ##
  674. ## The ``operation`` parameter should be an expression which uses the variables
  675. ## ``a`` and ``b`` for each step of the fold. The ``first`` parameter is the
  676. ## start value (the first ``a``) and therefor defines the type of the result.
  677. ##
  678. ## See also:
  679. ## * `foldr template<#foldr.t,untyped,untyped>`_
  680. ##
  681. runnableExamples:
  682. let
  683. numbers = @[0, 8, 1, 5]
  684. digits = foldl(numbers, a & (chr(b + ord('0'))), "")
  685. assert digits == "0815"
  686. var result: type(first)
  687. result = first
  688. for x in items(sequence):
  689. let
  690. a {.inject.} = result
  691. b {.inject.} = x
  692. result = operation
  693. result
  694. template foldr*(sequence, operation: untyped): untyped =
  695. ## Template to fold a sequence from right to left, returning the accumulation.
  696. ##
  697. ## The sequence is required to have at least a single element. Debug versions
  698. ## of your program will assert in this situation but release versions will
  699. ## happily go ahead. If the sequence has a single element it will be returned
  700. ## without applying ``operation``.
  701. ##
  702. ## The ``operation`` parameter should be an expression which uses the
  703. ## variables ``a`` and ``b`` for each step of the fold. Since this is a right
  704. ## fold, for non associative binary operations like subtraction think that
  705. ## the sequence of numbers 1, 2 and 3 will be parenthesized as (1 - (2 -
  706. ## (3))).
  707. ##
  708. ## See also:
  709. ## * `foldl template<#foldl.t,untyped,untyped>`_
  710. ## * `foldl template<#foldl.t,,,>`_ with a starting parameter
  711. ##
  712. runnableExamples:
  713. let
  714. numbers = @[5, 9, 11]
  715. addition = foldr(numbers, a + b)
  716. subtraction = foldr(numbers, a - b)
  717. multiplication = foldr(numbers, a * b)
  718. words = @["nim", "is", "cool"]
  719. concatenation = foldr(words, a & b)
  720. assert addition == 25, "Addition is (5+(9+(11)))"
  721. assert subtraction == 7, "Subtraction is (5-(9-(11)))"
  722. assert multiplication == 495, "Multiplication is (5*(9*(11)))"
  723. assert concatenation == "nimiscool"
  724. let s = sequence
  725. assert s.len > 0, "Can't fold empty sequences"
  726. var result: type(s[0])
  727. result = sequence[s.len - 1]
  728. for i in countdown(s.len - 2, 0):
  729. let
  730. a {.inject.} = s[i]
  731. b {.inject.} = result
  732. result = operation
  733. result
  734. template mapIt*(s: typed, op: untyped): untyped =
  735. ## Returns a new sequence with the results of `op` proc applied to every
  736. ## item in the container `s`.
  737. ##
  738. ## Since the input is not modified you can use it to
  739. ## transform the type of the elements in the input container.
  740. ##
  741. ## The template injects the ``it`` variable which you can use directly in an
  742. ## expression.
  743. ##
  744. ## See also:
  745. ## * `map proc<#map,openArray[T],proc(T)>`_
  746. ## * `applyIt template<#applyIt.t,untyped,untyped>`_ for the in-place version
  747. ##
  748. runnableExamples:
  749. let
  750. nums = @[1, 2, 3, 4]
  751. strings = nums.mapIt($(4 * it))
  752. assert strings == @["4", "8", "12", "16"]
  753. when defined(nimHasTypeof):
  754. type OutType = typeof((
  755. block:
  756. var it{.inject.}: typeof(items(s), typeOfIter);
  757. op), typeOfProc)
  758. else:
  759. type OutType = type((
  760. block:
  761. var it{.inject.}: type(items(s));
  762. op))
  763. when compiles(s.len):
  764. block: # using a block avoids https://github.com/nim-lang/Nim/issues/8580
  765. # BUG: `evalOnceAs(s2, s, false)` would lead to C compile errors
  766. # (`error: use of undeclared identifier`) instead of Nim compile errors
  767. evalOnceAs(s2, s, compiles((let _ = s)))
  768. var i = 0
  769. var result = newSeq[OutType](s2.len)
  770. for it {.inject.} in s2:
  771. result[i] = op
  772. i += 1
  773. result
  774. else:
  775. var result: seq[OutType] = @[]
  776. for it {.inject.} in s:
  777. result.add(op)
  778. result
  779. template mapIt*(s, typ, op: untyped): untyped {.error:
  780. "Deprecated since v0.12; Use 'mapIt(seq1, op)' - without specifying the type of the returned sequence".} =
  781. var result: seq[typ] = @[]
  782. for it {.inject.} in items(s):
  783. result.add(op)
  784. result
  785. template applyIt*(varSeq, op: untyped) =
  786. ## Convenience template around the mutable ``apply`` proc to reduce typing.
  787. ##
  788. ## The template injects the ``it`` variable which you can use directly in an
  789. ## expression. The expression has to return the same type as the sequence you
  790. ## are mutating.
  791. ##
  792. ## See also:
  793. ## * `apply proc<#apply,openArray[T],proc(T)_2>`_
  794. ## * `mapIt template<#mapIt.t,typed,untyped>`_
  795. ##
  796. runnableExamples:
  797. var nums = @[1, 2, 3, 4]
  798. nums.applyIt(it * 3)
  799. assert nums[0] + nums[3] == 15
  800. for i in low(varSeq) .. high(varSeq):
  801. let it {.inject.} = varSeq[i]
  802. varSeq[i] = op
  803. template newSeqWith*(len: int, init: untyped): untyped =
  804. ## Creates a new sequence of length `len`, calling `init` to initialize
  805. ## each value of the sequence.
  806. ##
  807. ## Useful for creating "2D" sequences - sequences containing other sequences
  808. ## or to populate fields of the created sequence.
  809. ##
  810. runnableExamples:
  811. ## Creates a sequence containing 5 bool sequences, each of length of 3.
  812. var seq2D = newSeqWith(5, newSeq[bool](3))
  813. assert seq2D.len == 5
  814. assert seq2D[0].len == 3
  815. assert seq2D[4][2] == false
  816. ## Creates a sequence of 20 random numbers from 1 to 10
  817. import random
  818. var seqRand = newSeqWith(20, rand(10))
  819. var result = newSeq[type(init)](len)
  820. for i in 0 ..< len:
  821. result[i] = init
  822. result
  823. proc mapLitsImpl(constructor: NimNode; op: NimNode; nested: bool;
  824. filter = nnkLiterals): NimNode =
  825. if constructor.kind in filter:
  826. result = newNimNode(nnkCall, lineInfoFrom = constructor)
  827. result.add op
  828. result.add constructor
  829. else:
  830. result = copyNimNode(constructor)
  831. for v in constructor:
  832. if nested or v.kind in filter:
  833. result.add mapLitsImpl(v, op, nested, filter)
  834. else:
  835. result.add v
  836. macro mapLiterals*(constructor, op: untyped;
  837. nested = true): untyped =
  838. ## Applies ``op`` to each of the **atomic** literals like ``3``
  839. ## or ``"abc"`` in the specified ``constructor`` AST. This can
  840. ## be used to map every array element to some target type:
  841. ##
  842. ## Example:
  843. ##
  844. ## .. code-block::
  845. ## let x = mapLiterals([0.1, 1.2, 2.3, 3.4], int)
  846. ## doAssert x is array[4, int]
  847. ##
  848. ## Short notation for:
  849. ##
  850. ## .. code-block::
  851. ## let x = [int(0.1), int(1.2), int(2.3), int(3.4)]
  852. ##
  853. ## If ``nested`` is true (which is the default), the literals are replaced
  854. ## everywhere in the ``constructor`` AST, otherwise only the first level
  855. ## is considered:
  856. ##
  857. ## .. code-block::
  858. ## let a = mapLiterals((1.2, (2.3, 3.4), 4.8), int)
  859. ## let b = mapLiterals((1.2, (2.3, 3.4), 4.8), int, nested=false)
  860. ## assert a == (1, (2, 3), 4)
  861. ## assert b == (1, (2.3, 3.4), 4)
  862. ##
  863. ## let c = mapLiterals((1, (2, 3), 4, (5, 6)), `$`)
  864. ## let d = mapLiterals((1, (2, 3), 4, (5, 6)), `$`, nested=false)
  865. ## assert c == ("1", ("2", "3"), "4", ("5", "6"))
  866. ## assert d == ("1", (2, 3), "4", (5, 6))
  867. ##
  868. ## There are no constraints for the ``constructor`` AST, it
  869. ## works for nested tuples of arrays of sets etc.
  870. result = mapLitsImpl(constructor, op, nested.boolVal)
  871. iterator items*[T](xs: iterator: T): T =
  872. ## iterates over each element yielded by a closure iterator. This may
  873. ## not seem particularly useful on its own, but this allows closure
  874. ## iterators to be used by the the mapIt, filterIt, allIt, anyIt, etc.
  875. ## templates.
  876. for x in xs():
  877. yield x
  878. when isMainModule:
  879. import strutils
  880. from algorithm import sorted
  881. # helper for testing double substitution side effects which are handled
  882. # by `evalOnceAs`
  883. var counter = 0
  884. proc identity[T](a: T): auto =
  885. counter.inc
  886. a
  887. block: # concat test
  888. let
  889. s1 = @[1, 2, 3]
  890. s2 = @[4, 5]
  891. s3 = @[6, 7]
  892. total = concat(s1, s2, s3)
  893. assert total == @[1, 2, 3, 4, 5, 6, 7]
  894. block: # count test
  895. let
  896. s1 = @[1, 2, 3, 2]
  897. s2 = @['a', 'b', 'x', 'a']
  898. a1 = [1, 2, 3, 2]
  899. a2 = ['a', 'b', 'x', 'a']
  900. r0 = count(s1, 0)
  901. r1 = count(s1, 1)
  902. r2 = count(s1, 2)
  903. r3 = count(s2, 'y')
  904. r4 = count(s2, 'x')
  905. r5 = count(s2, 'a')
  906. ar0 = count(a1, 0)
  907. ar1 = count(a1, 1)
  908. ar2 = count(a1, 2)
  909. ar3 = count(a2, 'y')
  910. ar4 = count(a2, 'x')
  911. ar5 = count(a2, 'a')
  912. assert r0 == 0
  913. assert r1 == 1
  914. assert r2 == 2
  915. assert r3 == 0
  916. assert r4 == 1
  917. assert r5 == 2
  918. assert ar0 == 0
  919. assert ar1 == 1
  920. assert ar2 == 2
  921. assert ar3 == 0
  922. assert ar4 == 1
  923. assert ar5 == 2
  924. block: # cycle tests
  925. let
  926. a = @[1, 2, 3]
  927. b: seq[int] = @[]
  928. c = [1, 2, 3]
  929. doAssert a.cycle(3) == @[1, 2, 3, 1, 2, 3, 1, 2, 3]
  930. doAssert a.cycle(0) == @[]
  931. #doAssert a.cycle(-1) == @[] # will not compile!
  932. doAssert b.cycle(3) == @[]
  933. doAssert c.cycle(3) == @[1, 2, 3, 1, 2, 3, 1, 2, 3]
  934. doAssert c.cycle(0) == @[]
  935. block: # repeat tests
  936. assert repeat(10, 5) == @[10, 10, 10, 10, 10]
  937. assert repeat(@[1, 2, 3], 2) == @[@[1, 2, 3], @[1, 2, 3]]
  938. assert repeat([1, 2, 3], 2) == @[[1, 2, 3], [1, 2, 3]]
  939. block: # deduplicates test
  940. let
  941. dup1 = @[1, 1, 3, 4, 2, 2, 8, 1, 4]
  942. dup2 = @["a", "a", "c", "d", "d"]
  943. dup3 = [1, 1, 3, 4, 2, 2, 8, 1, 4]
  944. dup4 = ["a", "a", "c", "d", "d"]
  945. unique1 = deduplicate(dup1)
  946. unique2 = deduplicate(dup2)
  947. unique3 = deduplicate(dup3)
  948. unique4 = deduplicate(dup4)
  949. unique5 = deduplicate(dup1.sorted, true)
  950. unique6 = deduplicate(dup2, true)
  951. unique7 = deduplicate(dup3.sorted, true)
  952. unique8 = deduplicate(dup4, true)
  953. assert unique1 == @[1, 3, 4, 2, 8]
  954. assert unique2 == @["a", "c", "d"]
  955. assert unique3 == @[1, 3, 4, 2, 8]
  956. assert unique4 == @["a", "c", "d"]
  957. assert unique5 == @[1, 2, 3, 4, 8]
  958. assert unique6 == @["a", "c", "d"]
  959. assert unique7 == @[1, 2, 3, 4, 8]
  960. assert unique8 == @["a", "c", "d"]
  961. block: # zip test
  962. let
  963. short = @[1, 2, 3]
  964. long = @[6, 5, 4, 3, 2, 1]
  965. words = @["one", "two", "three"]
  966. ashort = [1, 2, 3]
  967. along = [6, 5, 4, 3, 2, 1]
  968. awords = ["one", "two", "three"]
  969. zip1 = zip(short, long)
  970. zip2 = zip(short, words)
  971. zip3 = zip(ashort, along)
  972. zip4 = zip(ashort, awords)
  973. zip5 = zip(ashort, words)
  974. assert zip1 == @[(1, 6), (2, 5), (3, 4)]
  975. assert zip2 == @[(1, "one"), (2, "two"), (3, "three")]
  976. assert zip3 == @[(1, 6), (2, 5), (3, 4)]
  977. assert zip4 == @[(1, "one"), (2, "two"), (3, "three")]
  978. assert zip5 == @[(1, "one"), (2, "two"), (3, "three")]
  979. assert zip1[2].b == 4
  980. assert zip2[2].b == "three"
  981. assert zip3[2].b == 4
  982. assert zip4[2].b == "three"
  983. assert zip5[2].b == "three"
  984. block: # distribute tests
  985. let numbers = @[1, 2, 3, 4, 5, 6, 7]
  986. doAssert numbers.distribute(3) == @[@[1, 2, 3], @[4, 5], @[6, 7]]
  987. doAssert numbers.distribute(6)[0] == @[1, 2]
  988. doAssert numbers.distribute(6)[5] == @[7]
  989. let a = @[1, 2, 3, 4, 5, 6, 7]
  990. doAssert a.distribute(1, true) == @[@[1, 2, 3, 4, 5, 6, 7]]
  991. doAssert a.distribute(1, false) == @[@[1, 2, 3, 4, 5, 6, 7]]
  992. doAssert a.distribute(2, true) == @[@[1, 2, 3, 4], @[5, 6, 7]]
  993. doAssert a.distribute(2, false) == @[@[1, 2, 3, 4], @[5, 6, 7]]
  994. doAssert a.distribute(3, true) == @[@[1, 2, 3], @[4, 5], @[6, 7]]
  995. doAssert a.distribute(3, false) == @[@[1, 2, 3], @[4, 5, 6], @[7]]
  996. doAssert a.distribute(4, true) == @[@[1, 2], @[3, 4], @[5, 6], @[7]]
  997. doAssert a.distribute(4, false) == @[@[1, 2], @[3, 4], @[5, 6], @[7]]
  998. doAssert a.distribute(5, true) == @[@[1, 2], @[3, 4], @[5], @[6], @[7]]
  999. doAssert a.distribute(5, false) == @[@[1, 2], @[3, 4], @[5, 6], @[7], @[]]
  1000. doAssert a.distribute(6, true) == @[@[1, 2], @[3], @[4], @[5], @[6], @[7]]
  1001. doAssert a.distribute(6, false) == @[
  1002. @[1, 2], @[3, 4], @[5, 6], @[7], @[], @[]]
  1003. doAssert a.distribute(8, false) == a.distribute(8, true)
  1004. doAssert a.distribute(90, false) == a.distribute(90, true)
  1005. var b = @[0]
  1006. for f in 1 .. 25: b.add(f)
  1007. doAssert b.distribute(5, true)[4].len == 5
  1008. doAssert b.distribute(5, false)[4].len == 2
  1009. block: # map test
  1010. let
  1011. numbers = @[1, 4, 5, 8, 9, 7, 4]
  1012. anumbers = [1, 4, 5, 8, 9, 7, 4]
  1013. m1 = map(numbers, proc(x: int): int = 2*x)
  1014. m2 = map(anumbers, proc(x: int): int = 2*x)
  1015. assert m1 == @[2, 8, 10, 16, 18, 14, 8]
  1016. assert m2 == @[2, 8, 10, 16, 18, 14, 8]
  1017. block: # apply test
  1018. var a = @["1", "2", "3", "4"]
  1019. apply(a, proc(x: var string) = x &= "42")
  1020. assert a == @["142", "242", "342", "442"]
  1021. block: # filter proc test
  1022. let
  1023. colors = @["red", "yellow", "black"]
  1024. acolors = ["red", "yellow", "black"]
  1025. f1 = filter(colors, proc(x: string): bool = x.len < 6)
  1026. f2 = filter(colors) do (x: string) -> bool: x.len > 5
  1027. f3 = filter(acolors, proc(x: string): bool = x.len < 6)
  1028. f4 = filter(acolors) do (x: string) -> bool: x.len > 5
  1029. assert f1 == @["red", "black"]
  1030. assert f2 == @["yellow"]
  1031. assert f3 == @["red", "black"]
  1032. assert f4 == @["yellow"]
  1033. block: # filter iterator test
  1034. let numbers = @[1, 4, 5, 8, 9, 7, 4]
  1035. let anumbers = [1, 4, 5, 8, 9, 7, 4]
  1036. assert toSeq(filter(numbers, proc (x: int): bool = x mod 2 == 0)) ==
  1037. @[4, 8, 4]
  1038. assert toSeq(filter(anumbers, proc (x: int): bool = x mod 2 == 0)) ==
  1039. @[4, 8, 4]
  1040. block: # keepIf test
  1041. var floats = @[13.0, 12.5, 5.8, 2.0, 6.1, 9.9, 10.1]
  1042. keepIf(floats, proc(x: float): bool = x > 10)
  1043. assert floats == @[13.0, 12.5, 10.1]
  1044. block: # delete tests
  1045. let outcome = @[1, 1, 1, 1, 1, 1, 1, 1]
  1046. var dest = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1]
  1047. dest.delete(3, 8)
  1048. assert outcome == dest, """\
  1049. Deleting range 3-9 from [1,1,1,2,2,2,2,2,2,1,1,1,1,1]
  1050. is [1,1,1,1,1,1,1,1]"""
  1051. block: # insert tests
  1052. var dest = @[1, 1, 1, 1, 1, 1, 1, 1]
  1053. let
  1054. src = @[2, 2, 2, 2, 2, 2]
  1055. outcome = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1]
  1056. dest.insert(src, 3)
  1057. assert dest == outcome, """\
  1058. Inserting [2,2,2,2,2,2] into [1,1,1,1,1,1,1,1]
  1059. at 3 is [1,1,1,2,2,2,2,2,2,1,1,1,1,1]"""
  1060. block: # filterIt test
  1061. let
  1062. temperatures = @[-272.15, -2.0, 24.5, 44.31, 99.9, -113.44]
  1063. acceptable = filterIt(temperatures, it < 50 and it > -10)
  1064. notAcceptable = filterIt(temperatures, it > 50 or it < -10)
  1065. assert acceptable == @[-2.0, 24.5, 44.31]
  1066. assert notAcceptable == @[-272.15, 99.9, -113.44]
  1067. block: # keepItIf test
  1068. var candidates = @["foo", "bar", "baz", "foobar"]
  1069. keepItIf(candidates, it.len == 3 and it[0] == 'b')
  1070. assert candidates == @["bar", "baz"]
  1071. block: # all
  1072. let
  1073. numbers = @[1, 4, 5, 8, 9, 7, 4]
  1074. anumbers = [1, 4, 5, 8, 9, 7, 4]
  1075. len0seq: seq[int] = @[]
  1076. assert all(numbers, proc (x: int): bool = return x < 10) == true
  1077. assert all(numbers, proc (x: int): bool = return x < 9) == false
  1078. assert all(len0seq, proc (x: int): bool = return false) == true
  1079. assert all(anumbers, proc (x: int): bool = return x < 10) == true
  1080. assert all(anumbers, proc (x: int): bool = return x < 9) == false
  1081. block: # allIt
  1082. let
  1083. numbers = @[1, 4, 5, 8, 9, 7, 4]
  1084. anumbers = [1, 4, 5, 8, 9, 7, 4]
  1085. len0seq: seq[int] = @[]
  1086. assert allIt(numbers, it < 10) == true
  1087. assert allIt(numbers, it < 9) == false
  1088. assert allIt(len0seq, false) == true
  1089. assert allIt(anumbers, it < 10) == true
  1090. assert allIt(anumbers, it < 9) == false
  1091. block: # any
  1092. let
  1093. numbers = @[1, 4, 5, 8, 9, 7, 4]
  1094. anumbers = [1, 4, 5, 8, 9, 7, 4]
  1095. len0seq: seq[int] = @[]
  1096. assert any(numbers, proc (x: int): bool = return x > 8) == true
  1097. assert any(numbers, proc (x: int): bool = return x > 9) == false
  1098. assert any(len0seq, proc (x: int): bool = return true) == false
  1099. assert any(anumbers, proc (x: int): bool = return x > 8) == true
  1100. assert any(anumbers, proc (x: int): bool = return x > 9) == false
  1101. block: # anyIt
  1102. let
  1103. numbers = @[1, 4, 5, 8, 9, 7, 4]
  1104. anumbers = [1, 4, 5, 8, 9, 7, 4]
  1105. len0seq: seq[int] = @[]
  1106. assert anyIt(numbers, it > 8) == true
  1107. assert anyIt(numbers, it > 9) == false
  1108. assert anyIt(len0seq, true) == false
  1109. assert anyIt(anumbers, it > 8) == true
  1110. assert anyIt(anumbers, it > 9) == false
  1111. block: # toSeq test
  1112. block:
  1113. let
  1114. numeric = @[1, 2, 3, 4, 5, 6, 7, 8, 9]
  1115. odd_numbers = toSeq(filter(numeric) do (x: int) -> bool:
  1116. if x mod 2 == 1:
  1117. result = true)
  1118. assert odd_numbers == @[1, 3, 5, 7, 9]
  1119. block:
  1120. doAssert [1, 2].toSeq == @[1, 2]
  1121. doAssert @[1, 2].toSeq == @[1, 2]
  1122. doAssert @[1, 2].toSeq == @[1, 2]
  1123. doAssert toSeq(@[1, 2]) == @[1, 2]
  1124. block:
  1125. iterator myIter(seed: int): auto =
  1126. for i in 0..<seed:
  1127. yield i
  1128. doAssert toSeq(myIter(2)) == @[0, 1]
  1129. block:
  1130. iterator myIter(): auto {.inline.} =
  1131. yield 1
  1132. yield 2
  1133. doAssert myIter.toSeq == @[1, 2]
  1134. doAssert toSeq(myIter) == @[1, 2]
  1135. block:
  1136. iterator myIter(): int {.closure.} =
  1137. yield 1
  1138. yield 2
  1139. doAssert myIter.toSeq == @[1, 2]
  1140. doAssert toSeq(myIter) == @[1, 2]
  1141. block:
  1142. proc myIter(): auto =
  1143. iterator ret(): int {.closure.} =
  1144. yield 1
  1145. yield 2
  1146. result = ret
  1147. doAssert myIter().toSeq == @[1, 2]
  1148. doAssert toSeq(myIter()) == @[1, 2]
  1149. block:
  1150. proc myIter(n: int): auto =
  1151. var counter = 0
  1152. iterator ret(): int {.closure.} =
  1153. while counter < n:
  1154. yield counter
  1155. counter.inc
  1156. result = ret
  1157. block:
  1158. let myIter3 = myIter(3)
  1159. doAssert myIter3.toSeq == @[0, 1, 2]
  1160. block:
  1161. let myIter3 = myIter(3)
  1162. doAssert toSeq(myIter3) == @[0, 1, 2]
  1163. block:
  1164. # makes sure this does not hang forever
  1165. doAssert myIter(3).toSeq == @[0, 1, 2]
  1166. doAssert toSeq(myIter(3)) == @[0, 1, 2]
  1167. block:
  1168. # tests https://github.com/nim-lang/Nim/issues/7187
  1169. counter = 0
  1170. let ret = toSeq(@[1, 2, 3].identity().filter(proc (x: int): bool = x < 3))
  1171. doAssert ret == @[1, 2]
  1172. doAssert counter == 1
  1173. block: # foldl tests
  1174. let
  1175. numbers = @[5, 9, 11]
  1176. addition = foldl(numbers, a + b)
  1177. subtraction = foldl(numbers, a - b)
  1178. multiplication = foldl(numbers, a * b)
  1179. words = @["nim", "is", "cool"]
  1180. concatenation = foldl(words, a & b)
  1181. assert addition == 25, "Addition is (((5)+9)+11)"
  1182. assert subtraction == -15, "Subtraction is (((5)-9)-11)"
  1183. assert multiplication == 495, "Multiplication is (((5)*9)*11)"
  1184. assert concatenation == "nimiscool"
  1185. block: # foldr tests
  1186. let
  1187. numbers = @[5, 9, 11]
  1188. addition = foldr(numbers, a + b)
  1189. subtraction = foldr(numbers, a - b)
  1190. multiplication = foldr(numbers, a * b)
  1191. words = @["nim", "is", "cool"]
  1192. concatenation = foldr(words, a & b)
  1193. assert addition == 25, "Addition is (5+(9+(11)))"
  1194. assert subtraction == 7, "Subtraction is (5-(9-(11)))"
  1195. assert multiplication == 495, "Multiplication is (5*(9*(11)))"
  1196. assert concatenation == "nimiscool"
  1197. block: # mapIt + applyIt test
  1198. counter = 0
  1199. var
  1200. nums = @[1, 2, 3, 4]
  1201. strings = nums.identity.mapIt($(4 * it))
  1202. doAssert counter == 1
  1203. nums.applyIt(it * 3)
  1204. assert nums[0] + nums[3] == 15
  1205. assert strings[2] == "12"
  1206. block: # newSeqWith tests
  1207. var seq2D = newSeqWith(4, newSeq[bool](2))
  1208. seq2D[0][0] = true
  1209. seq2D[1][0] = true
  1210. seq2D[0][1] = true
  1211. doAssert seq2D == @[@[true, true], @[true, false], @[false, false], @[false, false]]
  1212. block: # mapLiterals tests
  1213. let x = mapLiterals([0.1, 1.2, 2.3, 3.4], int)
  1214. doAssert x is array[4, int]
  1215. doAssert mapLiterals((1, ("abc"), 2), float, nested = false) ==
  1216. (float(1), "abc", float(2))
  1217. doAssert mapLiterals(([1], ("abc"), 2), `$`, nested = true) ==
  1218. (["1"], "abc", "2")
  1219. block: # mapIt with openArray
  1220. counter = 0
  1221. proc foo(x: openArray[int]): seq[int] = x.mapIt(it * 10)
  1222. doAssert foo([identity(1), identity(2)]) == @[10, 20]
  1223. doAssert counter == 2
  1224. block: # mapIt with direct openArray
  1225. proc foo1(x: openArray[int]): seq[int] = x.mapIt(it * 10)
  1226. counter = 0
  1227. doAssert foo1(openArray[int]([identity(1), identity(2)])) == @[10, 20]
  1228. doAssert counter == 2
  1229. # Corner cases (openArray literals should not be common)
  1230. template foo2(x: openArray[int]): seq[int] = x.mapIt(it * 10)
  1231. counter = 0
  1232. doAssert foo2(openArray[int]([identity(1), identity(2)])) == @[10, 20]
  1233. # TODO: this fails; not sure how to fix this case
  1234. # doAssert counter == 2
  1235. counter = 0
  1236. doAssert openArray[int]([identity(1), identity(2)]).mapIt(it) == @[1, 2]
  1237. # ditto
  1238. # doAssert counter == 2
  1239. block: # mapIt empty test, see https://github.com/nim-lang/Nim/pull/8584#pullrequestreview-144723468
  1240. # NOTE: `[].mapIt(it)` is illegal, just as `let a = @[]` is (lacks type
  1241. # of elements)
  1242. doAssert: not compiles(mapIt(@[], it))
  1243. doAssert: not compiles(mapIt([], it))
  1244. doAssert newSeq[int](0).mapIt(it) == @[]
  1245. block: # mapIt redifinition check, see https://github.com/nim-lang/Nim/issues/8580
  1246. let s2 = [1, 2].mapIt(it)
  1247. doAssert s2 == @[1, 2]
  1248. block:
  1249. counter = 0
  1250. doAssert [1, 2].identity().mapIt(it*2).mapIt(it*10) == @[20, 40]
  1251. # https://github.com/nim-lang/Nim/issues/7187 test case
  1252. doAssert counter == 1
  1253. block: # mapIt with invalid RHS for `let` (#8566)
  1254. type X = enum
  1255. A, B
  1256. doAssert mapIt(X, $it) == @["A", "B"]
  1257. block:
  1258. # bug #9093
  1259. let inp = "a:b,c:d"
  1260. let outp = inp.split(",").mapIt(it.split(":"))
  1261. doAssert outp == @[@["a", "b"], @["c", "d"]]
  1262. block:
  1263. proc iter(len: int): auto =
  1264. result = iterator(): int =
  1265. for i in 0..<len:
  1266. yield i
  1267. doAssert: iter(3).mapIt(2*it).foldl(a + b) == 6
  1268. when not defined(testing):
  1269. echo "Finished doc tests"