module Data.List.EitherFunctions
( partlyMap
, groupEither
, spanLeft
, spanRight
) where
import Data.Either (Either (..))
import Data.List (map)
import Data.Maybe (Maybe (..), maybe)
partlyMap :: (a -> Maybe b) -> [a] -> [Either a b]
partlyMap f = map (\x -> maybe (Left x) Right (f x))
groupEither :: [Either a b] -> [Either [a] [b]]
groupEither [] = []
groupEither ((Left x) : xs) = let (ys, zs) = spanLeft xs
in Left (x : ys) : groupEither zs
groupEither ((Right x) : xs) = let (ys, zs) = spanRight xs
in Right (x : ys) : groupEither zs
spanLeft :: [Either a b] -> ([a], [Either a b])
spanLeft [] = ([], [])
spanLeft ((Left x) : xs) = let (ys, zs) = spanLeft xs
in (x : ys, zs)
spanLeft xs = ([], xs)
spanRight :: [Either a b] -> ([b], [Either a b])
spanRight [] = ([], [])
spanRight ((Right x) : xs) = let (ys, zs) = spanRight xs
in (x : ys, zs)
spanRight xs = ([], xs)