Class.hs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. {-# LANGUAGE TypeSynonymInstances #-}
  2. {-# LANGUAGE FlexibleInstances #-}
  3. {- |
  4. Type class for textual data and simple (fromItegral like) conversion
  5. between them.
  6. The conversion utility here, although simple may not be the fastest one
  7. available, and aims at preserving the textual representation of data,
  8. not its binary structure. This, given the existence of codecs with
  9. ambiguous representation means that the following function may evaluate
  10. to False:
  11. mayBeFalse :: Textual a => a -> Bool
  12. mayBeFalse a = let
  13. b = fromText a
  14. in a == b
  15. -}
  16. module Data.Textual.Class where
  17. import Data.String
  18. import qualified Data.ByteString as SB
  19. import qualified Data.ByteString.Lazy as LB
  20. import qualified Codec.Binary.UTF8.String as UTF8
  21. import qualified Data.Text as ST
  22. import qualified Data.Text.Lazy as LT
  23. {- | Type class for data structures that are logically text -}
  24. class IsString a => Textual a where
  25. toString :: a -> String
  26. instance Textual String where
  27. toString = id
  28. {- | With UTF-8 encoding -}
  29. instance Textual SB.ByteString where
  30. toString = UTF8.decode . SB.unpack
  31. {- | With UTF-8 encoding -}
  32. instance Textual LB.ByteString where
  33. toString = UTF8.decode . LB.unpack
  34. instance Textual ST.Text where
  35. toString = ST.unpack
  36. {- | Converts between instances of Textual -}
  37. fromTextual :: (Textual a, Textual b) => a -> b
  38. fromTextual = fromString . toString