sequtils.nim 37 KB

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