-- File created: 2008-03-23 20:09:47

module Coadjute.Util.Misc
   ( eitherToMaybe
   , mread
   , partitionEithers
   , plural
   ) where

import Data.Char (isSpace)

partitionEithers :: [Either a b] -> ([a], [b])
partitionEithers = foldr (either left right) ([],[])
 where
   left  a (l, r) = (a:l, r)
   right a (l, r) = (l, a:r)

eitherToMaybe :: Either a b -> Maybe b
eitherToMaybe = either (const Nothing) Just

-- |Like @Prelude.read@, but gives @Nothing@ on failure or ambiguity.
mread :: Read a => String -> Maybe a
mread s =
   case reads s of
        [(x,r)] -> if all isSpace r then Just x else Nothing
        _       -> Nothing

plural :: Integral a => a -> String
plural 1 = ""
plural _ = "s"