sequtils.nim 36 KB

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