Advertisement
Guest User

Untitled

a guest
Oct 17th, 2018
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Nim 0.93 KB | None | 0 0
  1. template partitionIt*[T](s: openArray[T], pred: untyped): tuple[t: seq[T], f: seq[T]] =
  2.   ## Returns a tuple that contains two sequences.
  3.   ## The first sequence contains the items that fulfill the predicate.
  4.   ## The second sequence contains the items that do not fulfill the predicate.
  5.   runnableExamples:
  6.     import sequtils
  7.     let
  8.       temperatures = @[-272.15, -2.0, 24.5, 44.31, 99.9, -113.44]
  9.       acceptable = filterIt(temperatures, it < 50 and it > -10)
  10.       notAcceptable = filterIt(temperatures, it > 50 or it < -10)
  11.       partitions = partitionIt(temperatures, it < 50 and it > -10)
  12.     assert acceptable == @[-2.0, 24.5, 44.31]
  13.     assert notAcceptable == @[-272.15, 99.9, -113.44]
  14.     assert partitions[0] == acceptable
  15.     assert partitions[1] == notAcceptable
  16.  
  17.   var
  18.     t = newSeq[T]()
  19.     f = newSeq[T]()
  20.   for it {.inject.} in items(s):
  21.     if pred:
  22.       t &= it
  23.     else:
  24.       f &= it
  25.   (t: t, f: f)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement