{-# LANGUAGE FlexibleContexts  #-}
{-# LANGUAGE FlexibleInstances #-}
module System.Environment.FromEnv.TryParse
(
    TryParse (..)
)
where

import           Data.Text (Text)
import qualified Data.Text as T
import           Text.Read (readMaybe)

-- | Class for things that may be parsed from strings.
class TryParse a where
  tryParse :: String -> Maybe a

instance TryParse Int where tryParse :: String -> Maybe Int
tryParse = forall a. Read a => String -> Maybe a
readMaybe
instance TryParse Double where tryParse :: String -> Maybe Double
tryParse = forall a. Read a => String -> Maybe a
readMaybe
instance TryParse Float where tryParse :: String -> Maybe Float
tryParse = forall a. Read a => String -> Maybe a
readMaybe

instance TryParse [Char] where
   tryParse :: String -> Maybe String
tryParse = forall a. a -> Maybe a
Just

instance TryParse Char where
   tryParse :: String -> Maybe Char
tryParse [Char
c] = forall a. a -> Maybe a
Just Char
c
   tryParse String
_   = forall a. Maybe a
Nothing

instance TryParse Text where
  tryParse :: String -> Maybe Text
tryParse = forall a. a -> Maybe a
Just forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Text
T.pack

instance TryParse Bool where
  tryParse :: String -> Maybe Bool
tryParse String
"" = forall a. a -> Maybe a
Just Bool
False
  tryParse String
_  = forall a. a -> Maybe a
Just Bool
True