@@ -202,6 +202,69 @@ pub fn last[A](self : Array[A]) -> A? {
202
202
}
203
203
}
204
204
205
+ ///| Zips two arrays into a single array of tuples.
206
+ ///
207
+ /// Parameters:
208
+ ///
209
+ /// * `l` : The first array.
210
+ /// * `r` : The second array.
211
+ ///
212
+ /// Returns an array of tuples, where each tuple contains corresponding elements
213
+ /// from the two input arrays.
214
+ ///
215
+ /// Example:
216
+ ///
217
+ /// ```moonbit
218
+ /// test "zip" {
219
+ /// let arr1 = [1, 2, 3]
220
+ /// let arr2 = ['a', 'b', 'c']
221
+ /// inspect!(zip(arr1, arr2), content="[(1, 'a'), (2, 'b'), (3, 'c')]")
222
+ /// }
223
+ /// ```
224
+ pub fn zip [A , B ](l : Array [A ], r : Array [B ]) -> Array [(A , B )] {
225
+ let length = if l .length () < r .length () { l .length () } else { r .length () }
226
+ let arr = Array ::new (capacity = length )
227
+ for i = 0 ; i < length ; i = i + 1 {
228
+ arr .push ((l [i ], r [i ]))
229
+ } else {
230
+ return arr
231
+ }
232
+ }
233
+
234
+ ///| Zips two arrays into a single array by applying a function to each pair of elements.
235
+ ///
236
+ /// Parameters:
237
+ ///
238
+ /// * `l` : The first array.
239
+ /// * `r` : The second array.
240
+ /// * `f` : A function that takes two arguments, one from each array, and returns a value.
241
+ ///
242
+ /// Returns an array containing the results of applying the function to each pair of elements.
243
+ ///
244
+ /// Example:
245
+ ///
246
+ /// ```moonbit
247
+ /// test "zip_with" {
248
+ /// let arr1 = [1, 2, 3]
249
+ /// let arr2 = [4, 5, 6]
250
+ /// let add = fn(a, b) { a + b }
251
+ /// inspect!(zip_with(arr1, arr2, merge=add), content="[5, 7, 9]")
252
+ /// }
253
+ /// ```
254
+ pub fn zip_with [A , B , C ](
255
+ l : Array [A ],
256
+ r : Array [B ],
257
+ merge ~ : (A , B ) -> C
258
+ ) -> Array [C ] {
259
+ let length = if l .length () < r .length () { l .length () } else { r .length () }
260
+ let arr = Array ::new (capacity = length )
261
+ for i = 0 ; i < length ; i = i + 1 {
262
+ arr .push (merge (l [i ], r [i ]))
263
+ } else {
264
+ return arr
265
+ }
266
+ }
267
+
205
268
///|
206
269
pub impl [X : @quickcheck .Arbitrary ] @quickcheck .Arbitrary for Array [X ] with arbitrary (
207
270
size ,
0 commit comments