_plist.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. from ._compat import Sequence, Hashable
  2. from numbers import Integral
  3. from functools import reduce
  4. class _PListBuilder(object):
  5. """
  6. Helper class to allow construction of a list without
  7. having to reverse it in the end.
  8. """
  9. __slots__ = ('_head', '_tail')
  10. def __init__(self):
  11. self._head = _EMPTY_PLIST
  12. self._tail = _EMPTY_PLIST
  13. def _append(self, elem, constructor):
  14. if not self._tail:
  15. self._head = constructor(elem)
  16. self._tail = self._head
  17. else:
  18. self._tail.rest = constructor(elem)
  19. self._tail = self._tail.rest
  20. return self._head
  21. def append_elem(self, elem):
  22. return self._append(elem, lambda e: PList(e, _EMPTY_PLIST))
  23. def append_plist(self, pl):
  24. return self._append(pl, lambda l: l)
  25. def build(self):
  26. return self._head
  27. class _PListBase(object):
  28. __slots__ = ('__weakref__',)
  29. # Selected implementations can be taken straight from the Sequence
  30. # class, other are less suitable. Especially those that work with
  31. # index lookups.
  32. count = Sequence.count
  33. index = Sequence.index
  34. def __reduce__(self):
  35. # Pickling support
  36. return plist, (list(self),)
  37. def __len__(self):
  38. """
  39. Return the length of the list, computed by traversing it.
  40. This is obviously O(n) but with the current implementation
  41. where a list is also a node the overhead of storing the length
  42. in every node would be quite significant.
  43. """
  44. return sum(1 for _ in self)
  45. def __repr__(self):
  46. return "plist({0})".format(list(self))
  47. __str__ = __repr__
  48. def cons(self, elem):
  49. """
  50. Return a new list with elem inserted as new head.
  51. >>> plist([1, 2]).cons(3)
  52. plist([3, 1, 2])
  53. """
  54. return PList(elem, self)
  55. def mcons(self, iterable):
  56. """
  57. Return a new list with all elements of iterable repeatedly cons:ed to the current list.
  58. NB! The elements will be inserted in the reverse order of the iterable.
  59. Runs in O(len(iterable)).
  60. >>> plist([1, 2]).mcons([3, 4])
  61. plist([4, 3, 1, 2])
  62. """
  63. head = self
  64. for elem in iterable:
  65. head = head.cons(elem)
  66. return head
  67. def reverse(self):
  68. """
  69. Return a reversed version of list. Runs in O(n) where n is the length of the list.
  70. >>> plist([1, 2, 3]).reverse()
  71. plist([3, 2, 1])
  72. Also supports the standard reversed function.
  73. >>> reversed(plist([1, 2, 3]))
  74. plist([3, 2, 1])
  75. """
  76. result = plist()
  77. head = self
  78. while head:
  79. result = result.cons(head.first)
  80. head = head.rest
  81. return result
  82. __reversed__ = reverse
  83. def split(self, index):
  84. """
  85. Spilt the list at position specified by index. Returns a tuple containing the
  86. list up until index and the list after the index. Runs in O(index).
  87. >>> plist([1, 2, 3, 4]).split(2)
  88. (plist([1, 2]), plist([3, 4]))
  89. """
  90. lb = _PListBuilder()
  91. right_list = self
  92. i = 0
  93. while right_list and i < index:
  94. lb.append_elem(right_list.first)
  95. right_list = right_list.rest
  96. i += 1
  97. if not right_list:
  98. # Just a small optimization in the cases where no split occurred
  99. return self, _EMPTY_PLIST
  100. return lb.build(), right_list
  101. def __iter__(self):
  102. li = self
  103. while li:
  104. yield li.first
  105. li = li.rest
  106. def __lt__(self, other):
  107. if not isinstance(other, _PListBase):
  108. return NotImplemented
  109. return tuple(self) < tuple(other)
  110. def __eq__(self, other):
  111. """
  112. Traverses the lists, checking equality of elements.
  113. This is an O(n) operation, but preserves the standard semantics of list equality.
  114. """
  115. if not isinstance(other, _PListBase):
  116. return NotImplemented
  117. self_head = self
  118. other_head = other
  119. while self_head and other_head:
  120. if not self_head.first == other_head.first:
  121. return False
  122. self_head = self_head.rest
  123. other_head = other_head.rest
  124. return not self_head and not other_head
  125. def __getitem__(self, index):
  126. # Don't use this this data structure if you plan to do a lot of indexing, it is
  127. # very inefficient! Use a PVector instead!
  128. if isinstance(index, slice):
  129. if index.start is not None and index.stop is None and (index.step is None or index.step == 1):
  130. return self._drop(index.start)
  131. # Take the easy way out for all other slicing cases, not much structural reuse possible anyway
  132. return plist(tuple(self)[index])
  133. if not isinstance(index, Integral):
  134. raise TypeError("'%s' object cannot be interpreted as an index" % type(index).__name__)
  135. if index < 0:
  136. # NB: O(n)!
  137. index += len(self)
  138. try:
  139. return self._drop(index).first
  140. except AttributeError:
  141. raise IndexError("PList index out of range")
  142. def _drop(self, count):
  143. if count < 0:
  144. raise IndexError("PList index out of range")
  145. head = self
  146. while count > 0:
  147. head = head.rest
  148. count -= 1
  149. return head
  150. def __hash__(self):
  151. return hash(tuple(self))
  152. def remove(self, elem):
  153. """
  154. Return new list with first element equal to elem removed. O(k) where k is the position
  155. of the element that is removed.
  156. Raises ValueError if no matching element is found.
  157. >>> plist([1, 2, 1]).remove(1)
  158. plist([2, 1])
  159. """
  160. builder = _PListBuilder()
  161. head = self
  162. while head:
  163. if head.first == elem:
  164. return builder.append_plist(head.rest)
  165. builder.append_elem(head.first)
  166. head = head.rest
  167. raise ValueError('{0} not found in PList'.format(elem))
  168. class PList(_PListBase):
  169. """
  170. Classical Lisp style singly linked list. Adding elements to the head using cons is O(1).
  171. Element access is O(k) where k is the position of the element in the list. Taking the
  172. length of the list is O(n).
  173. Fully supports the Sequence and Hashable protocols including indexing and slicing but
  174. if you need fast random access go for the PVector instead.
  175. Do not instantiate directly, instead use the factory functions :py:func:`l` or :py:func:`plist` to
  176. create an instance.
  177. Some examples:
  178. >>> x = plist([1, 2])
  179. >>> y = x.cons(3)
  180. >>> x
  181. plist([1, 2])
  182. >>> y
  183. plist([3, 1, 2])
  184. >>> y.first
  185. 3
  186. >>> y.rest == x
  187. True
  188. >>> y[:2]
  189. plist([3, 1])
  190. """
  191. __slots__ = ('first', 'rest')
  192. def __new__(cls, first, rest):
  193. instance = super(PList, cls).__new__(cls)
  194. instance.first = first
  195. instance.rest = rest
  196. return instance
  197. def __bool__(self):
  198. return True
  199. __nonzero__ = __bool__
  200. Sequence.register(PList)
  201. Hashable.register(PList)
  202. class _EmptyPList(_PListBase):
  203. __slots__ = ()
  204. def __bool__(self):
  205. return False
  206. __nonzero__ = __bool__
  207. @property
  208. def first(self):
  209. raise AttributeError("Empty PList has no first")
  210. @property
  211. def rest(self):
  212. return self
  213. Sequence.register(_EmptyPList)
  214. Hashable.register(_EmptyPList)
  215. _EMPTY_PLIST = _EmptyPList()
  216. def plist(iterable=(), reverse=False):
  217. """
  218. Creates a new persistent list containing all elements of iterable.
  219. Optional parameter reverse specifies if the elements should be inserted in
  220. reverse order or not.
  221. >>> plist([1, 2, 3])
  222. plist([1, 2, 3])
  223. >>> plist([1, 2, 3], reverse=True)
  224. plist([3, 2, 1])
  225. """
  226. if not reverse:
  227. iterable = list(iterable)
  228. iterable.reverse()
  229. return reduce(lambda pl, elem: pl.cons(elem), iterable, _EMPTY_PLIST)
  230. def l(*elements):
  231. """
  232. Creates a new persistent list containing all arguments.
  233. >>> l(1, 2, 3)
  234. plist([1, 2, 3])
  235. """
  236. return plist(elements)