]> Git ā€” Sourcephile - comptalang.git/blob - lib/Hcompta/Lib/Foldable.hs
Correction : Calc.Balance.infer_equilibrium
[comptalang.git] / lib / Hcompta / Lib / Foldable.hs
1 module Hcompta.Lib.Foldable where
2
3 import Data.Monoid
4 import Data.Maybe (listToMaybe, maybeToList)
5 import Data.Foldable (Foldable, foldMap, foldr)
6
7 -- | Return the first non-'Nothing' returned by the given function
8 -- applied on the elements of a 'Foldable'.
9 find :: Foldable t => (a -> Maybe b) -> t a -> Maybe b
10 find f = listToMaybe . Data.Foldable.foldMap (maybeToList . f)
11
12 -- | Like 'Data.Either.partitionEithers' but generalized
13 -- to work on a 'Foldable' containing 'Monoid's.
14 --
15 -- NOTE: any lazyness on resulting 'Monoid's is preserved.
16 partitionEithers
17 :: (Foldable t, Monoid r, Monoid l)
18 => t (Either l r) -> (l, r)
19 partitionEithers m =
20 Data.Foldable.foldr (either left right) (mempty, mempty) m
21 where
22 left a ~(l, r) = (a`mappend`l, r)
23 right a ~(l, r) = (l, a`mappend`r)
24
25 -- | Return a tuple of accumulated 'Left's and folded 'Right's
26 -- in the given 'Foldable'.
27 --
28 -- NOTE: any lazyness on resulting 'Left'sā€™ 'Monoid' is preserved.
29 accumLeftsAndFoldrRights
30 :: (Foldable t, Monoid l)
31 => (r -> ra -> ra) -> ra -> t (Either l r) -> (l, ra)
32 accumLeftsAndFoldrRights f rempty m =
33 Data.Foldable.foldr (either left right) (mempty, rempty) m
34 where
35 left a ~(l, r) = (a`mappend`l, r)
36 right a ~(l, r) = (l, f a r)