@@ -53,6 +53,91 @@ test "from_array" {
53
53
@assertion .assert_eq (pq .peek (), Some (5 ))?
54
54
}
55
55
56
+ fn copy_node [T ](x : Node [T ]) -> Node [T ] {
57
+ match x {
58
+ Nil => Nil
59
+ Cons (top ) =>
60
+ Cons (
61
+ {
62
+ content : top .content,
63
+ sibling : copy_node (top .sibling),
64
+ child : copy_node (top .child),
65
+ },
66
+ )
67
+ }
68
+ }
69
+
70
+ /// Return a copy of the queue.
71
+ ///
72
+ /// # Example
73
+ /// ```
74
+ /// let queue : PriorityQueue[Int] = PriorityQueue::[1, 2, 3, 4]
75
+ /// let queue2 : PriorityQueue[Int] = PriorityQueue.copy()
76
+ /// ```
77
+ pub fn copy [T ](self : PriorityQueue [T ]) -> PriorityQueue [T ] {
78
+ let new_que : PriorityQueue [T ] = { len : self .len, top : copy_node (self .top) }
79
+ new_que
80
+ }
81
+
82
+ test "copy" {
83
+ let v = PriorityQueue ::[1 , 2 , 3 , 4 ]
84
+ let ve = v .copy ()
85
+ inspect (v .peek ().to_string (), content = "Some(4)" )?
86
+ inspect (ve .peek ().to_string (), content = "Some(4)" )?
87
+ v .pop () |> ignore
88
+ inspect (v .peek ().to_string (), content = "Some(3)" )?
89
+ inspect (ve .peek ().to_string (), content = "Some(4)" )?
90
+ }
91
+
92
+ pub fn to_array [T : Compare ](self : PriorityQueue [T ]) -> Array [T ] {
93
+ let arr : Array [T ] = []
94
+ fn go (x : Node [T ]) {
95
+ match x {
96
+ Cons (node ) => {
97
+ arr .push (node .content)
98
+ go (node .sibling)
99
+ go (node .child)
100
+ }
101
+ Nil => ()
102
+ }
103
+ }
104
+
105
+ go (self .top)
106
+ arr .sort_by (fn (x , y ) { if x < y { 1 } else { - 1 } })
107
+ arr
108
+ }
109
+
110
+ test "to_array" {
111
+ let v = PriorityQueue ::[1 , 2 , 3 , 4 ]
112
+ inspect (v .to_array ().to_string (), content = "[4, 3, 2, 1]" )?
113
+ inspect (v .to_array ().to_string (), content = "[4, 3, 2, 1]" )?
114
+ }
115
+
116
+ pub fn as_iter [T : Compare ](self : PriorityQueue [T ]) -> @iter .Iter [T ] {
117
+ @iter .Iter ::_unstable_internal_make (
118
+ fn (yield ) {
119
+ let arr = self .to_array ()
120
+ for i = 0 ; i < arr .length (); i = i + 1 {
121
+ if yield (arr [i ]).not () {
122
+ break false
123
+ }
124
+ } else {
125
+ true
126
+ }
127
+ },
128
+ )
129
+ }
130
+
131
+ test "as_iter" {
132
+ let buf = Buffer ::make (20 )
133
+ let v = PriorityQueue ::[1 , 2 , 3 ]
134
+ v .as_iter ().iter (fn (e ) { buf .write_string ("[\(e)]" ) })
135
+ inspect (buf , content = "[3][2][1]" )?
136
+ buf .reset ()
137
+ v .as_iter ().take (2 ).iter (fn (e ) { buf .write_string ("[\(e)]" ) })
138
+ inspect (buf , content = "[3][2]" )?
139
+ }
140
+
56
141
fn meld [T : Compare ](x : Node [T ], y : Node [T ]) -> Node [T ] {
57
142
match (x , y ) {
58
143
(Nil , _ ) => y
0 commit comments