iteration.fnl 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. ;;; Lispy-Fennel (LF) --- The Functional Fennel Library
  2. ;;;
  3. ;;; Copyright (C) 2020 Kevin "The Nuclear" Bloom <nuclearkev@dragora.org>
  4. ;;;
  5. ;;; This file is part of LF.
  6. ;;;
  7. ;;; LF is free software: you can redistribute it and/or modify
  8. ;;; it under the terms of the MIT License.
  9. ;;;
  10. ;;; LF is distributed in the hope that it will be useful,
  11. ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;;; MIT License for more details.
  14. ;;;
  15. ;;; You should have received a copy of the MIT License
  16. ;;; along with LF. If not, see <https://opensource.org/licenses/MIT>.
  17. (local iteration {})
  18. (fn iteration.map [f l]
  19. (var map [])
  20. (when (> (length l) 0)
  21. (each
  22. [k v (ipairs l)]
  23. (table.insert map (f v))))
  24. map)
  25. (fn iteration.filter [f l]
  26. (var filtered [])
  27. (each
  28. [k v (ipairs l)]
  29. (when (f v)
  30. (table.insert filtered v)))
  31. filtered)
  32. (fn iteration.filter-map [f l]
  33. (var filtered [])
  34. (each
  35. [k v (ipairs l)]
  36. (let [new-v (f v)]
  37. (when new-v
  38. (table.insert filtered new-v))))
  39. filtered)
  40. (fn iteration.reduce [f d l]
  41. (var prev d)
  42. (each
  43. [k cur (ipairs l)]
  44. (let [new-v (f prev cur)]
  45. (set prev new-v)))
  46. prev)
  47. iteration