A simple IRC bot written in Haskell
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Configuration.hs 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, ExistentialQuantification, GADTs #-}
  2. module Network.IRC.Configuration
  3. ( Name
  4. , Value (..)
  5. , Configuration
  6. , Configurable (..)
  7. , fromMap
  8. , lookup
  9. , require
  10. , lookupDefault
  11. ) where
  12. import qualified ClassyPrelude as P
  13. import ClassyPrelude hiding (lookup)
  14. import Data.Maybe (fromJust)
  15. type Name = Text
  16. class Configurable a where
  17. fromValue :: Value -> Maybe a
  18. valueToList :: Value -> Maybe [a]
  19. valueToList (List xs) = mapM fromValue xs
  20. valueToList _ = Nothing
  21. toValue :: a -> Value
  22. listToValue :: [a] -> Value
  23. listToValue = List . map toValue
  24. valueToNum :: (Num a) => Value -> Maybe a
  25. valueToNum (Number n) = Just . fromInteger $ n
  26. valueToNum _ = Nothing
  27. instance Configurable Integer where
  28. fromValue = valueToNum
  29. toValue = Number
  30. instance Configurable Int where
  31. fromValue = valueToNum
  32. toValue = Number . toInteger
  33. instance Configurable Text where
  34. fromValue (String s) = Just s
  35. fromValue _ = Nothing
  36. toValue = String
  37. instance Configurable Bool where
  38. fromValue (Boolean b) = Just b
  39. fromValue _ = Nothing
  40. toValue = Boolean
  41. instance Configurable a => Configurable [a] where
  42. fromValue = valueToList
  43. toValue = listToValue
  44. data Value = String Text
  45. | Number Integer
  46. | Boolean Bool
  47. | List [Value]
  48. deriving (Eq, Show)
  49. newtype Configuration = Configuration { configMap :: Map Name Value } deriving (Show)
  50. fromMap :: Map Name Value -> Configuration
  51. fromMap = Configuration
  52. lookup :: (Configurable a) => Name -> Configuration -> Maybe a
  53. lookup name Configuration {..} = join . map fromValue $ P.lookup name configMap
  54. require :: (Configurable a) => Name -> Configuration -> a
  55. require n = fromJust . lookup n
  56. lookupDefault :: (Configurable a) => Name -> Configuration -> a -> a
  57. lookupDefault n c v = fromMaybe v $ lookup n c