Add minBy and maxBy to Util

This commit is contained in:
Nathan McCarty 2025-01-29 01:31:20 -05:00
parent 5ad68cdb44
commit 3addc0aeaf

View file

@ -16,6 +16,44 @@ import Data.Fin
%default total
```
## Foldable
General utility functions for foldables
```idris hide
namespace Foldable
```
### minBy
```idris
||| Get the minimum element of a collection using the provided comparison
||| function and seed value
export
minBy : Foldable f => (cmp : a -> a -> Ordering) -> (acc : a) -> f a -> a
minBy cmp acc x =
foldl
(\acc, e =>
case e `cmp` acc of
LT => e
_ => acc)
acc x
```
```idris
||| Get the maximum element of a collection using the provided comparison
||| function and seed value
export
maxBy : Foldable f => (cmp : a -> a -> Ordering) -> (acc : a) -> f a -> a
maxBy cmp acc x =
foldl
(\acc, e =>
case e `cmp` acc of
GT => e
_ => acc)
acc x
```
## Functions
### repeatN
@ -138,13 +176,28 @@ Lazily generate all the permutations of a Vect
(y, z :: ys) :: map (consSnd y) (select (z :: ys))
```
### minBy and maxBy
```idris
||| Get the minimum element of a non-empty vector by using the provided
||| comparison function
export
minBy : (f : a -> a -> Ordering) -> Vect (S n) a -> a
minBy f (x :: xs) = Foldable.minBy f x xs
||| Get the maximum element of a non-empty vector by using the provided
||| comparison function
export
maxBy : (f : a -> a -> Ordering) -> Vect (S n) a -> a
maxBy f (x :: xs) = Foldable.maxBy f x xs
```
## Fin
```idris hide
namespace Fin
```
```idris
||| Decriment a Fin, wrapping on overflow
export