lists.scad 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // List helpers
  2. /*!
  3. Flattens a list one level:
  4. flatten([[0,1],[2,3]]) => [0,1,2,3]
  5. */
  6. function flatten(list) = [ for (i = list, v = i) v ];
  7. /*!
  8. Creates a list from a range:
  9. range([0:2:6]) => [0,2,4,6]
  10. */
  11. function range(r) = [ for(x=r) x ];
  12. /*!
  13. Reverses a list:
  14. reverse([1,2,3]) => [3,2,1]
  15. */
  16. function reverse(list) = [for (i = [len(list)-1:-1:0]) list[i]];
  17. /*!
  18. Extracts a subarray from index begin (inclusive) to end (exclusive)
  19. FIXME: Change name to use list instead of array?
  20. subarray([1,2,3,4], 1, 2) => [2,3]
  21. */
  22. function subarray(list,begin=0,end=-1) = [
  23. let(end = end < 0 ? len(list) : end)
  24. for (i = [begin : 1 : end-1])
  25. list[i]
  26. ];
  27. /*!
  28. Returns a copy of a list with the element at index i set to x
  29. set([1,2,3,4], 2, 5) => [1,2,5,4]
  30. */
  31. function set(list, i, x) = [for (i_=[0:len(list)-1]) i == i_ ? x : list[i_]];
  32. /*!
  33. Remove element from the list by index.
  34. remove([4,3,2,1],1) => [4,2,1]
  35. */
  36. function remove(list, i) = [for (i_=[0:1:len(list)-2]) list[i_ < i ? i_ : i_ + 1]];