{-# LANGUAGE BlockArguments, LambdaCase, NoImplicitPrelude #-}

-- | Functions involving lists of 'Either'.

module Data.List.EitherFunctions
  (

    {- * Map       -}  partlyMap,
    {- * Group     -}  groupEither,
    {- * Partition -}  partition,
    {- * Span      -}  spanLeft, spanLeft', spanRight, spanRight',
    {- * Lead      -}  leadLeft, leadLeft', leadRight, leadRight',
    {- * Branch    -}  branchLeft, branchRight, BranchComparison

  ) where

import Data.Bool                   ( Bool (..) )
import Data.Either                 ( Either (..) )
import Data.Function               ( fix )
import Data.Functor.Contravariant  ( Comparison (..), contramap )
import Data.List                   ( foldr, map, span )
import Data.Tree                   ( Tree (..), Forest )
import Data.Maybe                  ( Maybe (..), maybe )
import Data.Ord                    ( Ordering (..) )

-- |
-- >>> import Prelude (even, show)
--
-- >>> partlyMap (\x -> if even x then Just (show x) else Nothing) [1..5]
-- [Left 1,Right "2",Left 3,Right "4",Left 5]

partlyMap :: (a -> Maybe b) -> [a] -> [Either a b]

partlyMap :: (a -> Maybe b) -> [a] -> [Either a b]
partlyMap a -> Maybe b
f = (a -> Either a b) -> [a] -> [Either a b]
forall a b. (a -> b) -> [a] -> [b]
map \a
x -> Either a b -> (b -> Either a b) -> Maybe b -> Either a b
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (a -> Either a b
forall a b. a -> Either a b
Left a
x) b -> Either a b
forall a b. b -> Either a b
Right (a -> Maybe b
f a
x)

-- |
-- >>> groupEither [Left 1, Left 2, Right 'a', Left 3, Right 'b', Right 'c']
-- [Left [1,2],Right "a",Left [3],Right "bc"]

groupEither :: [Either a b] -> [Either [a] [b]]

groupEither :: [Either a b] -> [Either [a] [b]]
groupEither = (([Either a b] -> [Either [a] [b]])
 -> [Either a b] -> [Either [a] [b]])
-> [Either a b] -> [Either [a] [b]]
forall a. (a -> a) -> a
fix \[Either a b] -> [Either [a] [b]]
r -> \case
    []            ->  []
    Left  a
x : [Either a b]
xs  ->  [a] -> Either [a] [b]
forall a b. a -> Either a b
Left  (a
x a -> [a] -> [a]
forall a. a -> [a] -> [a]
: [a]
ys) Either [a] [b] -> [Either [a] [b]] -> [Either [a] [b]]
forall a. a -> [a] -> [a]
: [Either a b] -> [Either [a] [b]]
r [Either a b]
zs  where ([a]
ys, [Either a b]
zs) = [Either a b] -> ([a], [Either a b])
forall a b. [Either a b] -> ([a], [Either a b])
spanLeft  [Either a b]
xs
    Right b
x : [Either a b]
xs  ->  [b] -> Either [a] [b]
forall a b. b -> Either a b
Right (b
x b -> [b] -> [b]
forall a. a -> [a] -> [a]
: [b]
ys) Either [a] [b] -> [Either [a] [b]] -> [Either [a] [b]]
forall a. a -> [a] -> [a]
: [Either a b] -> [Either [a] [b]]
r [Either a b]
zs  where ([b]
ys, [Either a b]
zs) = [Either a b] -> ([b], [Either a b])
forall a b. [Either a b] -> ([b], [Either a b])
spanRight [Either a b]
xs

-- |
-- >>> leadLeft [Right 'a', Right 'b', Left 1, Right 'c', Right 'd', Left 2, Right 'e', Right 'f']
-- ("ab",[(1,"cd"),(2,"ef")])
--
-- >>> leadLeft [Left 1, Left 2, Right 'a', Left 3, Right 'b', Right 'c']
-- ("",[(1,""),(2,"a"),(3,"bc")])

leadLeft :: [Either a b] -> ([b], [(a, [b])])

leadLeft :: [Either a b] -> ([b], [(a, [b])])
leadLeft = [Either a b] -> ([b], [(a, [b])])
forall a b. [Either a b] -> ([b], [(a, [b])])
f
  where
    f :: [Either a b] -> ([b], [(a, [b])])
f [Either a b]
xs = ([b]
unledItems, [(a, [b])]
ledGroups)
      where
        ([b]
unledItems, Maybe (a, [Either a b])
ysMaybe) = [Either a b] -> ([b], Maybe (a, [Either a b]))
forall a b. [Either a b] -> ([b], Maybe (a, [Either a b]))
spanRight' [Either a b]
xs
        ledGroups :: [(a, [b])]
ledGroups = case Maybe (a, [Either a b])
ysMaybe of
            Maybe (a, [Either a b])
Nothing            ->  []
            Just (a
leader, [Either a b]
ys)  ->  a -> [Either a b] -> [(a, [b])]
forall a b. a -> [Either a b] -> [(a, [b])]
r a
leader [Either a b]
ys

    r :: a -> [Either a b] -> [(a, [b])]
r a
leader [Either a b]
xs = (a, [b])
firstGroup (a, [b]) -> [(a, [b])] -> [(a, [b])]
forall a. a -> [a] -> [a]
: [(a, [b])]
moreGroups
      where
        firstGroup :: (a, [b])
firstGroup = (a
leader, [b]
followers)
        ([b]
followers, Maybe (a, [Either a b])
ysMaybe) = [Either a b] -> ([b], Maybe (a, [Either a b]))
forall a b. [Either a b] -> ([b], Maybe (a, [Either a b]))
spanRight' [Either a b]
xs
        moreGroups :: [(a, [b])]
moreGroups = case Maybe (a, [Either a b])
ysMaybe of
            Maybe (a, [Either a b])
Nothing             ->  []
            Just (a
leader', [Either a b]
ys)  ->  a -> [Either a b] -> [(a, [b])]
r a
leader' [Either a b]
ys

-- |
-- >>> leadLeft' 0 [Right 'a', Right 'b', Left 1, Right 'c', Right 'd', Left 2, Right 'e', Right 'f']
-- [(0,"ab"),(1,"cd"),(2,"ef")]
--
-- >>> leadLeft' 0 [Left 1, Left 2, Right 'a', Left 3, Right 'b', Right 'c']
-- [(1,""),(2,"a"),(3,"bc")]

leadLeft' ::
    a -- ^ Leader to use for the first group in case the list does not begin with a 'Left'.
    -> [Either a b] -> [(a, [b])]

leadLeft' :: a -> [Either a b] -> [(a, [b])]
leadLeft' a
leader [Either a b]
xs = a -> ([b], [(a, [b])]) -> [(a, [b])]
forall a b. a -> ([b], [(a, [b])]) -> [(a, [b])]
addMissingLeader a
leader ([Either a b] -> ([b], [(a, [b])])
forall a b. [Either a b] -> ([b], [(a, [b])])
leadLeft [Either a b]
xs)

-- |
-- >>> leadRight [Left 1, Left 2, Right 'a', Left 3, Left 4, Right 'b', Left 5, Left 6]
-- ([1,2],[('a',[3,4]),('b',[5,6])])
--
-- >>> leadRight [Right 'a', Left 3, Left 4, Right 'b', Right 'c', Left 5, Left 6]
-- ([],[('a',[3,4]),('b',[]),('c',[5,6])])

leadRight :: [Either a b] -> ([a], [(b, [a])])

leadRight :: [Either a b] -> ([a], [(b, [a])])
leadRight = [Either a b] -> ([a], [(b, [a])])
forall a b. [Either a b] -> ([a], [(b, [a])])
f
  where
    f :: [Either a b] -> ([a], [(b, [a])])
f [Either a b]
xs = ([a]
unledItems, [(b, [a])]
ledGroups)
      where
        ([a]
unledItems, Maybe (b, [Either a b])
ysMaybe) = [Either a b] -> ([a], Maybe (b, [Either a b]))
forall a b. [Either a b] -> ([a], Maybe (b, [Either a b]))
spanLeft' [Either a b]
xs
        ledGroups :: [(b, [a])]
ledGroups = case Maybe (b, [Either a b])
ysMaybe of
            Maybe (b, [Either a b])
Nothing            ->  []
            Just (b
leader, [Either a b]
ys)  ->  b -> [Either a b] -> [(b, [a])]
forall a a. a -> [Either a a] -> [(a, [a])]
r b
leader [Either a b]
ys

    r :: a -> [Either a a] -> [(a, [a])]
r a
leader [Either a a]
xs = (a, [a])
firstGroup (a, [a]) -> [(a, [a])] -> [(a, [a])]
forall a. a -> [a] -> [a]
: [(a, [a])]
moreGroups
      where
        firstGroup :: (a, [a])
firstGroup = (a
leader, [a]
followers)
        ([a]
followers, Maybe (a, [Either a a])
ysMaybe) = [Either a a] -> ([a], Maybe (a, [Either a a]))
forall a b. [Either a b] -> ([a], Maybe (b, [Either a b]))
spanLeft' [Either a a]
xs
        moreGroups :: [(a, [a])]
moreGroups = case Maybe (a, [Either a a])
ysMaybe of
            Maybe (a, [Either a a])
Nothing             ->  []
            Just (a
leader', [Either a a]
ys)  ->  a -> [Either a a] -> [(a, [a])]
r a
leader' [Either a a]
ys

-- |
-- >>> leadRight' 'z' [Left 1, Left 2, Right 'a', Left 3, Left 4, Right 'b', Left 5, Left 6]
-- [('z',[1,2]),('a',[3,4]),('b',[5,6])]
--
-- >>> leadRight' 'z' [Right 'a', Left 3, Left 4, Right 'b', Right 'c', Left 5, Left 6]
-- [('a',[3,4]),('b',[]),('c',[5,6])]

leadRight' ::
    b -- ^ Leader to use for the first group in case the list does not begin with a 'Right'.
    -> [Either a b] -> [(b, [a])]

leadRight' :: b -> [Either a b] -> [(b, [a])]
leadRight' b
leader [Either a b]
xs = b -> ([a], [(b, [a])]) -> [(b, [a])]
forall a b. a -> ([b], [(a, [b])]) -> [(a, [b])]
addMissingLeader b
leader ([Either a b] -> ([a], [(b, [a])])
forall a b. [Either a b] -> ([a], [(b, [a])])
leadRight [Either a b]
xs)

addMissingLeader :: a -> ([b], [(a, [b])]) -> [(a, [b])]

addMissingLeader :: a -> ([b], [(a, [b])]) -> [(a, [b])]
addMissingLeader a
_      ( []         , [(a, [b])]
groups ) =                        [(a, [b])]
groups
addMissingLeader a
leader ( [b]
unledIntro , [(a, [b])]
groups ) = (a
leader, [b]
unledIntro) (a, [b]) -> [(a, [b])] -> [(a, [b])]
forall a. a -> [a] -> [a]
: [(a, [b])]
groups

-- |
-- >>> spanLeft [Left 1, Left 2, Right 'a', Left 3, Right 'b', Right 'c']
-- ([1,2],[Right 'a',Left 3,Right 'b',Right 'c'])
--
-- >>> spanLeft [Right 'a', Left 3, Right 'b', Right 'c']
-- ([],[Right 'a',Left 3,Right 'b',Right 'c'])

spanLeft :: [Either a b] -> ([a], [Either a b])

spanLeft :: [Either a b] -> ([a], [Either a b])
spanLeft = (([Either a b] -> ([a], [Either a b]))
 -> [Either a b] -> ([a], [Either a b]))
-> [Either a b] -> ([a], [Either a b])
forall a. (a -> a) -> a
fix \[Either a b] -> ([a], [Either a b])
r -> \case
    []           ->  ( []     , [] )
    Left a
x : [Either a b]
xs  ->  ( a
x a -> [a] -> [a]
forall a. a -> [a] -> [a]
: [a]
ys , [Either a b]
zs )  where ([a]
ys, [Either a b]
zs) = [Either a b] -> ([a], [Either a b])
r [Either a b]
xs
    [Either a b]
xs           ->  ( []     , [Either a b]
xs )

-- | Similar to 'spanLeft', but preserves a little more information in the return type: if the remainder of the list is non-empty, then it necessarily begins with a 'Right', and so we can go ahead and unwrap that and return it as a value of type `b`.
--
-- >>> spanLeft' [Left 1, Left 2, Right 'a', Left 3, Right 'b', Right 'c']
-- ([1,2],Just ('a',[Left 3,Right 'b',Right 'c']))
--
-- >>> spanLeft' [Right 'a', Left 3, Right 'b', Right 'c']
-- ([],Just ('a',[Left 3,Right 'b',Right 'c']))
--
-- >>> spanLeft' [Left 1, Left 2, Left 3]
-- ([1,2,3],Nothing)

spanLeft' :: [Either a b] -> ([a], Maybe (b, [Either a b]))

spanLeft' :: [Either a b] -> ([a], Maybe (b, [Either a b]))
spanLeft' = (([Either a b] -> ([a], Maybe (b, [Either a b])))
 -> [Either a b] -> ([a], Maybe (b, [Either a b])))
-> [Either a b] -> ([a], Maybe (b, [Either a b]))
forall a. (a -> a) -> a
fix \[Either a b] -> ([a], Maybe (b, [Either a b]))
r -> \case
    []            ->  ( []     , Maybe (b, [Either a b])
forall a. Maybe a
Nothing      )
    Left  a
x : [Either a b]
xs  ->  ( a
x a -> [a] -> [a]
forall a. a -> [a] -> [a]
: [a]
ys , Maybe (b, [Either a b])
zs           )  where ([a]
ys, Maybe (b, [Either a b])
zs) = [Either a b] -> ([a], Maybe (b, [Either a b]))
r [Either a b]
xs
    Right b
x : [Either a b]
xs  ->  ( []     , (b, [Either a b]) -> Maybe (b, [Either a b])
forall a. a -> Maybe a
Just (b
x, [Either a b]
xs) )

-- | Similar to 'spanRight', but preserves a little more information in the return type: if the remainder of the list is non-empty, then it necessarily begins with a 'Left', and so we can go ahead and unwrap that and return it as a value of type `a`.
--
-- >>> spanRight [Left 1, Left 2, Right 'a', Left 3, Right 'b', Right 'c']
-- ("",[Left 1,Left 2,Right 'a',Left 3,Right 'b',Right 'c'])
--
-- >>> spanRight [Right 'a', Left 3, Right 'b', Right 'c']
-- ("a",[Left 3,Right 'b',Right 'c'])

spanRight :: [Either a b] -> ([b], [Either a b])

spanRight :: [Either a b] -> ([b], [Either a b])
spanRight = (([Either a b] -> ([b], [Either a b]))
 -> [Either a b] -> ([b], [Either a b]))
-> [Either a b] -> ([b], [Either a b])
forall a. (a -> a) -> a
fix \[Either a b] -> ([b], [Either a b])
r -> \case
    []            ->  ( []     , [] )
    Right b
x : [Either a b]
xs  ->  ( b
x b -> [b] -> [b]
forall a. a -> [a] -> [a]
: [b]
ys , [Either a b]
zs )  where ([b]
ys, [Either a b]
zs) = [Either a b] -> ([b], [Either a b])
r [Either a b]
xs
    [Either a b]
xs            ->  ( []     , [Either a b]
xs )

-- |
-- >>> spanRight' [Left 1, Left 2, Right 'a', Left 3, Right 'b', Right 'c']
-- ("",Just (1,[Left 2,Right 'a',Left 3,Right 'b',Right 'c']))
--
-- >>> spanRight' [Right 'a', Left 3, Right 'b', Right 'c']
-- ("a",Just (3,[Right 'b',Right 'c']))
--
-- >>> spanRight' [Right 'a', Right 'b', Right 'c']
-- ("abc",Nothing)

spanRight' :: [Either a b] -> ([b], Maybe (a, [Either a b]))

spanRight' :: [Either a b] -> ([b], Maybe (a, [Either a b]))
spanRight' = (([Either a b] -> ([b], Maybe (a, [Either a b])))
 -> [Either a b] -> ([b], Maybe (a, [Either a b])))
-> [Either a b] -> ([b], Maybe (a, [Either a b]))
forall a. (a -> a) -> a
fix \[Either a b] -> ([b], Maybe (a, [Either a b]))
r -> \case
    []            ->  ( []     , Maybe (a, [Either a b])
forall a. Maybe a
Nothing      )
    Right b
x : [Either a b]
xs  ->  ( b
x b -> [b] -> [b]
forall a. a -> [a] -> [a]
: [b]
ys , Maybe (a, [Either a b])
zs           )  where ([b]
ys, Maybe (a, [Either a b])
zs) = [Either a b] -> ([b], Maybe (a, [Either a b]))
r [Either a b]
xs
    Left  a
x : [Either a b]
xs  ->  ( []     , (a, [Either a b]) -> Maybe (a, [Either a b])
forall a. a -> Maybe a
Just (a
x, [Either a b]
xs) )

-- |
-- >>> partition [Left 1, Left 2, Right 'a', Left 3, Right 'b', Right 'c']
-- ([1,2,3],"abc")

partition :: [Either a b] -> ([a], [b])

partition :: [Either a b] -> ([a], [b])
partition = (([Either a b] -> ([a], [b])) -> [Either a b] -> ([a], [b]))
-> [Either a b] -> ([a], [b])
forall a. (a -> a) -> a
fix \[Either a b] -> ([a], [b])
r -> \case
    []            ->  ( []     , []     )
    Left  a
a : [Either a b]
xs  ->  ( a
a a -> [a] -> [a]
forall a. a -> [a] -> [a]
: [a]
as , [b]
bs     )  where ([a]
as, [b]
bs) = [Either a b] -> ([a], [b])
r [Either a b]
xs
    Right b
b : [Either a b]
xs  ->  ( [a]
as     , b
b b -> [b] -> [b]
forall a. a -> [a] -> [a]
: [b]
bs )  where ([a]
as, [b]
bs) = [Either a b] -> ([a], [b])
r [Either a b]
xs

-- | The relative significance of branches (greater values are closer to the root).
type BranchComparison a = Comparison a

-- |
-- >>> import Prelude
--
-- >>> heading level title = Left (level, title)
-- >>> chapter = heading 1
-- >>> section = heading 2
-- >>> p text = Right text
--
-- >>> :{
-- >>> list =
-- >>>     [ p "Copyright"
-- >>>     , p "Preface"
-- >>>     , chapter "Animals"
-- >>>     , p "The kingdom animalia"
-- >>>     , section "Vertibrates"
-- >>>     , p "Cats"
-- >>>     , p "Snakes"
-- >>>     , section "Invertibrates"
-- >>>     , p "Worms"
-- >>>     , p "Jellyfishes"
-- >>>     , chapter "Fungus"
-- >>>     , p "Yeast"
-- >>>     , p "Truffles"
-- >>>     , p "Morels"
-- >>>     ]
-- >>> :}
--
-- >>> import Data.Functor.Contravariant
-- >>> flipComparison (Comparison f) = Comparison (flip f)
-- >>> headingComparison = contramap fst (flipComparison defaultComparison)
--
-- >>> (frontMatter, mainMatter) = branchLeft headingComparison list
--
-- >>> frontMatter
-- ["Copyright","Preface"]
--
-- >>> import Data.List
-- >>> showContent ((_, x), ys) = x ++ ": " ++ intercalate ", " ys
--
-- >>> import Data.Tree
-- >>> putStrLn $ drawForest $ map (fmap showContent) mainMatter
-- Animals: The kingdom animalia
-- |
-- +- Vertibrates: Cats, Snakes
-- |
-- `- Invertibrates: Worms, Jellyfishes
-- <BLANKLINE>
-- Fungus: Yeast, Truffles, Morels
-- <BLANKLINE>
-- <BLANKLINE>

branchLeft :: BranchComparison a -> [Either a b] -> ([b], Forest (a, [b]))

branchLeft :: BranchComparison a -> [Either a b] -> ([b], Forest (a, [b]))
branchLeft BranchComparison a
c [Either a b]
xs = ([b]
rejects, Forest (a, [b])
forest)
  where
    ([b]
rejects, [(a, [b])]
nodes) = [Either a b] -> ([b], [(a, [b])])
forall a b. [Either a b] -> ([b], [(a, [b])])
leadLeft [Either a b]
xs
    forest :: Forest (a, [b])
forest = BranchComparison (a, [b]) -> [(a, [b])] -> Forest (a, [b])
forall a. BranchComparison a -> [a] -> Forest a
makeForest BranchComparison (a, [b])
forall b. Comparison (a, b)
c' [(a, [b])]
nodes
    c' :: Comparison (a, b)
c' = ((a, b) -> a) -> BranchComparison a -> Comparison (a, b)
forall (f :: * -> *) a b. Contravariant f => (a -> b) -> f b -> f a
contramap (\(a
x, b
_) -> a
x) BranchComparison a
c

-- | Same as 'branchLeft', but with the types flipped; here, 'Right' is the case that indicates a branch.

branchRight :: BranchComparison b -> [Either a b] -> ([a], Forest (b, [a]))

branchRight :: BranchComparison b -> [Either a b] -> ([a], Forest (b, [a]))
branchRight BranchComparison b
c [Either a b]
xs = ([a]
rejects, Forest (b, [a])
forest)
  where
    ([a]
rejects, [(b, [a])]
nodes) = [Either a b] -> ([a], [(b, [a])])
forall a b. [Either a b] -> ([a], [(b, [a])])
leadRight [Either a b]
xs
    forest :: Forest (b, [a])
forest = BranchComparison (b, [a]) -> [(b, [a])] -> Forest (b, [a])
forall a. BranchComparison a -> [a] -> Forest a
makeForest BranchComparison (b, [a])
forall b. Comparison (b, b)
c' [(b, [a])]
nodes
    c' :: Comparison (b, b)
c' = ((b, b) -> b) -> BranchComparison b -> Comparison (b, b)
forall (f :: * -> *) a b. Contravariant f => (a -> b) -> f b -> f a
contramap (\(b
x, b
_) -> b
x) BranchComparison b
c

makeForest :: BranchComparison a -> [a] -> Forest a

makeForest :: BranchComparison a -> [a] -> Forest a
makeForest BranchComparison a
c = (a -> Forest a -> Forest a) -> Forest a -> [a] -> Forest a
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr a -> Forest a -> Forest a
f []
  where
    f :: a -> Forest a -> Forest a
f a
x Forest a
xs = a -> Forest a -> Tree a
forall a. a -> Forest a -> Tree a
Node a
x Forest a
chomped Tree a -> Forest a -> Forest a
forall a. a -> [a] -> [a]
: Forest a
remainder
      where
        (Forest a
chomped, Forest a
remainder) = (Tree a -> Bool) -> Forest a -> (Forest a, Forest a)
forall a. (a -> Bool) -> [a] -> ([a], [a])
span (\(Node a
y Forest a
_) -> a
x a -> a -> Bool
> a
y) Forest a
xs

    a
x > :: a -> a -> Bool
> a
y = case BranchComparison a -> a -> a -> Ordering
forall a. Comparison a -> a -> a -> Ordering
getComparison BranchComparison a
c a
x a
y of Ordering
GT -> Bool
True; Ordering
_ -> Bool
False