[bmx]Using Enumerations to iterate through a list backwards

Started by TomToad, April 03, 2018, 18:28:11

Previous topic - Next topic

TomToad

Title: TReverseableList
Author: TomToad
Posted: Apr 3, 2018

This extends the TList type so that you can iterate through it backwards with For/EachIn.  To use, create your list with Local List:TReverseableList = New TReverseableList.  The list acts like a normal TList.  To iterate through the list backwards using For/EachIn, just use For MyType = EachIn List.Backwards().  You can still iterate through it forwards in the normal way For MyType = Eachin List.
Code (blitzmax) Select
SuperStrict
'TReverseableList type
'  By TomToad
'  Released into public domain
'  use and modify as you please
'
'  Extends TList
'  everything in a TList works exactly as before
'  To use Eachin on the list backwards, just use
'        For Instance = Eachin List.Backwards()
'
'  Example at end of source.


Type TReverseableListEnum
Field _link:TLink

Method HasNext:Int()
Return _link._value<>_link
End Method

Method NextObject:Object()
Local value:Object=_link._value
Assert value<>_link
_link=_link._pred
Return value
End Method

End Type

Type TReverseableListHold
Field List:TReverseableList

Function Create:TReverseableListHold(List:TReverseableList)
Local ReverseableListHold:TReverseableListHold = New TReverseableListHold
ReverseableListHold.List = List
Return ReverseableListHold
End Function

Method ObjectEnumerator:TReverseableListEnum()
Local enum:TReverseableListEnum=New TReverseableListEnum
enum._link=List._head._pred
Return enum
End Method
End Type

Type TReverseableList Extends TList

Method Backwards:TReverseableListHold()
Return TReverseableListHold.Create(Self)
End Method

End Type

Local List:TReverseableList = New TReverseableList

List.AddLast("Anthony")
List.AddLast("Brian")
List.AddLast("Charles")
List.AddLast("Danny")

Print "~n--- populated list forwards"
For Local s:String = EachIn List
Print s
Next

Print "~n--- populated list backwards"
For Local s:String = EachIn List.backwards()
Print s
Next
------------------------------------------------
8 rabbits equals 1 rabbyte.