Monkey/Language/Lists
What are Lists?
[edit | edit source]In Monkey, lists are a set of objects that are encapsulated in an object, and read in a set sequential order. Lists have the power to be read forwards, backwards, traversed object-by-object, sorted, and offer a node-level access for insertion and queries.
Example:
Class Obj
Field x:Int, y:Int, z:Int
Method New(xx:Int,yy:Int,zz:Int)
x=xx; y=yy; z=zz
End
End
Function Main()
mylist = New List<Obj>
mylist.AddLast(New Obj(1,1,1))
mylist.AddLast(New Obj(2,2,2))
mylist.AddFirst(New Obj(3,3,3))
Print "list:"
For Local o:Obj = Eachin mylist
Print o.x+" "+o.y+" "+o.z
Next
End
A list is created like any other object with the 'NEW' keyword. It differs from other objects because it requires a type specifier. Type specifiers (or type parameters) are defined using the greater than-less than signs: < and >.
In the above example, the list 'mylist' is a list of 'Obj's, which is a class of three fields: x, y, and z.
'EachIn' will automatically iterate through a list, assigning the object to the iterating variable. EachIn will exit the loop when a NULL is reached, signaling the end of the list.
What are Nodes?
[edit | edit source]Syntax for a list's node:
Local mynode:list.Node<Obj>
mynode = mylist.FirstNode()
Nodes are also created when an object is added to a list:
Local mynode:list.Node<Obj> = mylist.AddLast(New Obj(4,4,4))
Nodes can return a value from the list:
Local o:Obj = mynode.Value()
Print o.x+" "+o.y+" "+o.z
Nodes can be used to iterate through a list backwards:
Local mynode:list.Node<Obj> = mylist.LastNode()
While mynode
Local o:Obj
o = mynode.Value()
Print o.x+" "+o.y+" "+o.z
mynode = mynode.PrevNode()
Wend
Nodes can insert a value into a list, using the Node constructor (the New command):
Local mynode:list.Node<Obj> = mylist.FirstNode()
Local insertdata:Obj = New Obj(9,9,9)
While mynode
If mynode.Value.x = 2
''insert after
New list.Node<Obj>( mynode.NextNode(), mynode, insertdata)
Endif
mynode = mynode.NextNode()
Wend
Nodes can remove a value from a list, although be sure to be done with that node before you remove it:
Local mynode:list.Node<Obj> = mylist.FirstNode()
Local removenode:list.Node<Obj>
While mynode
If mynode.Value.x = 2
''remove
removenode = mynode
Endif
mynode = mynode.NextNode()
removenode.Remove()
Wend