tfilter.nim 911 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. discard """
  2. output: "02468101214161820\n15"
  3. """
  4. proc filter[T](list: seq[T], f: proc (item: T): bool {.closure.}): seq[T] =
  5. result = @[]
  6. for i in items(list):
  7. if f(i):
  8. result.add(i)
  9. let nums = @[0, 1, 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
  10. when true:
  11. let nums2 = filter(nums,
  12. (proc (item: int): bool =
  13. result = (item mod 2) == 0)
  14. )
  15. proc outer =
  16. # lets use a proper closure this time:
  17. var modulo = 2
  18. let nums2 = filter(nums,
  19. (proc (item: int): bool = result = (item mod modulo) == 0)
  20. )
  21. for n in nums2: stdout.write(n)
  22. stdout.write("\n")
  23. outer()
  24. import math
  25. proc compose[T](f1, f2: proc (x: T): T {.closure.}): proc (x: T): T {.closure.} =
  26. result = (proc (x: T): T =
  27. result = f1(f2(x)))
  28. proc add5(x: int): int = result = x + 5
  29. var test = compose(add5, add5)
  30. echo test(5)