File tree Expand file tree Collapse file tree 2 files changed +88
-0
lines changed Expand file tree Collapse file tree 2 files changed +88
-0
lines changed Original file line number Diff line number Diff line change @@ -2311,3 +2311,55 @@ fn do_shuffle_by_pair_indexes(
2311
2311
float . compare ( a_pair . 0 , b_pair . 0 )
2312
2312
} )
2313
2313
}
2314
+
2315
+ /// Takes a list and a comparator, and returns the maximum element in the list
2316
+ ///
2317
+ ///
2318
+ /// ## Example
2319
+ ///
2320
+ /// ```gleam
2321
+ /// range(1, 10) |> list.max(int.compare)
2322
+ /// // -> Ok(10)
2323
+ /// ```
2324
+ ///
2325
+ /// ```gleam
2326
+ /// ["a", "c", "b"] |> list.max(string.compare)
2327
+ /// // -> Ok("c")
2328
+ /// ```
2329
+ pub fn max (
2330
+ over list : List ( a) ,
2331
+ with compare : fn ( a, a) -> Order ,
2332
+ ) -> Result ( a, Nil ) {
2333
+ reduce ( over : list , with : fn ( acc , other ) {
2334
+ case compare ( acc , other ) {
2335
+ order . Gt -> acc
2336
+ _ -> other
2337
+ }
2338
+ } )
2339
+ }
2340
+
2341
+ /// Takes a list and a comparator, and returns the minimum element in the list
2342
+ ///
2343
+ ///
2344
+ /// ## Example
2345
+ ///
2346
+ /// ```gleam
2347
+ /// range(1, 10) |> list.int(int.compare)
2348
+ /// // -> Ok(1)
2349
+ /// ```
2350
+ ///
2351
+ /// ```gleam
2352
+ /// ["a", "c", "b"] |> list.int(string.compare)
2353
+ /// // -> Ok("a")
2354
+ /// ```
2355
+ pub fn min (
2356
+ over list : List ( a) ,
2357
+ with compare : fn ( a, a) -> Order ,
2358
+ ) -> Result ( a, Nil ) {
2359
+ reduce ( over : list , with : fn ( acc , other ) {
2360
+ case compare ( acc , other ) {
2361
+ order . Lt -> acc
2362
+ _ -> other
2363
+ }
2364
+ } )
2365
+ }
Original file line number Diff line number Diff line change @@ -1281,3 +1281,39 @@ pub fn shuffle_test() {
1281
1281
list . range ( 0 , recursion_test_cycles )
1282
1282
|> list . shuffle ( )
1283
1283
}
1284
+
1285
+ pub fn max_test ( ) {
1286
+ [ ]
1287
+ |> list . max ( int . compare )
1288
+ |> should . equal ( Error ( Nil ) )
1289
+
1290
+ [ 1 , 3 , 2 ]
1291
+ |> list . max ( int . compare )
1292
+ |> should . equal ( Ok ( 3 ) )
1293
+
1294
+ [ -1.0 , 1.2 , 1.104 ]
1295
+ |> list . max ( float . compare )
1296
+ |> should . equal ( Ok ( 1.2 ) )
1297
+
1298
+ [ "a" , "c" , "b" ]
1299
+ |> list . max ( string . compare )
1300
+ |> should . equal ( Ok ( "c" ) )
1301
+ }
1302
+
1303
+ pub fn min_test ( ) {
1304
+ [ ]
1305
+ |> list . min ( int . compare )
1306
+ |> should . equal ( Error ( Nil ) )
1307
+
1308
+ [ 1 , 3 , 2 ]
1309
+ |> list . min ( int . compare )
1310
+ |> should . equal ( Ok ( 1 ) )
1311
+
1312
+ [ -1.0 , 1.2 , 1.104 ]
1313
+ |> list . min ( float . compare )
1314
+ |> should . equal ( Ok ( -1.0 ) )
1315
+
1316
+ [ "a" , "c" , "b" ]
1317
+ |> list . min ( string . compare )
1318
+ |> should . equal ( Ok ( "a" ) )
1319
+ }
You can’t perform that action at this time.
0 commit comments