How do I sort a collection, like a stack?
I’m thinking of something like this, except this obviously doesn’t work…
Monkey
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#Import"<std>"
Using std..
FunctionMain()
LocaltestStack:=NewSortingStack
ForLocaln:=1To20
LocalnewItem:=NewMyObject
newItem.depth=Rnd(0,100)
testStack.Push(newItem)
Next
testStack.Sort()'Doesn't do anything! :-/
ForLocaln:=EachintestStack
Print(n.depth)
Next
End
ClassSortingStack ExtendsStack<MyObject>
Method Compare:Int(a:MyObject,b:MyObject)
Ifa.depth>b.depth ThenReturn1
Ifa.depth=b.depth ThenReturn0
Return-1
End
End
ClassMyObject
Fielddepth:=0
End
Extended question: can I do it in monkey2 without extending the stack class, passing a function as an argument? How? I get confused because, in my example, the function that compares values requires you to specify the objects being compared, but how would I know those objects inside a For/Next loop, for each loop?
Never mind, I got this… sorted out
A quick look at the source code for stacks showed me what to do. No need to extend the Stack class:
Monkey
1
2
3
testStack.Sort(Lambda:Int(x:MyObject,y:MyObject)
Returnx.depth<=>y.depth
End)
New features like this (compared to Monkey1) are powerful, but are definitely counter-intuitive for noobs, and will take a while to wrap my head around it…
I find that simply overriding a “Compare” method would have been easier to read!