Concept
When you're crafting algorithms that have to modify a list, it's often easier to output a new list than modify the existing list since modifying the existing list requires you use a counter and set an element at the counter. Here's an example of writing a filter that includes all elements that are divisible by the next element in the list:
Is that not pretty? (Answer: Yes, that is not pretty.)
Here's a much prettier way of doing it:
Wow! It runs inline, and it's much shorter. Of course, I had to invert the logic and call remove, but it's pretty nice still.
List comprehensions benefit even more:
1 new_list = [ element for element in list if element mod element.next == 0 ]
Yes, you're not doing it inline, but it's pretty, isn't it?
API
SmartList class:
initialized with: SmartList(dumbList)
.unvisited_elements() -> returns SmartList
.newly_inserted_elements() -> returns SmartList
SmartElement class:
.next(), .prev() -> returns SmartElement
.remove() -> remove this element from the list
.all_other_elements() -> returns SmartList
.container() -> returns the SmartList that contains the element
.insertBefore(other_element) -> insert other_element before this element
.insertAfter(other_element) -> insert an other_element after this element
[Ruby] .insert other_element, :before
[Ruby] .insert other_element, :after
More Examples
