0 | module Chem.Util
 1 |
 2 | %default total
 3 |
 4 | ||| Extracts the minimal value from a list (if any) according to the
 5 | ||| given comparison function.
 6 | export
 7 | minBy : Ord b => (a -> b) -> List a -> Maybe a
 8 | minBy _ []     = Nothing
 9 | minBy f (h::t) = Just $ go h (f h) t
10 |   where
11 |     go : a -> b -> List a -> a
12 |     go va _  []        = va
13 |     go va vb (x :: xs) =
14 |       let vb2 := f x
15 |        in if vb <= vb2 then go va vb xs else go x vb2 xs
16 |
17 | ||| Modify those values in a functor that fulfill the given predicate
18 | export %inline
19 | mapIf : Functor f => (a -> Bool) -> (a -> a) -> f a -> f a
20 | mapIf p f = map $ \v => if p v then f v else v
21 |
22 | ||| Keep and modify those values in a list that fulfill the given predicate
23 | export %inline
24 | mapFilter : (a -> Bool) -> (a -> b) -> List a -> List b
25 | mapFilter p f = mapMaybe (\v => if p v then Just (f v) else Nothing)
26 |