diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..05d4d64 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.cabal-sandbox/ +cabal.sandbox.config +dist/ diff --git a/Data/Convertible/Utils.hs b/Data/Convertible/Utils.hs index 8c8a774..02df130 100644 --- a/Data/Convertible/Utils.hs +++ b/Data/Convertible/Utils.hs @@ -17,11 +17,13 @@ For license and copyright information, see the file LICENSE Portability: portable -} - module Data.Convertible.Utils(boundedConversion, - convertVia + convertVia, + convertMay ) where +import Control.Monad.Error (throwError) +import Control.Monad ((<=<)) import Data.Convertible.Base import Data.Typeable @@ -32,7 +34,7 @@ the source via 'safeConvert', comparing to the source value. Results in an erro if the conversion is out of bounds. -} boundedConversion :: (Ord a, Bounded b, Show a, Show b, Convertible a Integer, Convertible b Integer, - Typeable a, Typeable b) => + Typeable a, Typeable b) => (a -> ConvertResult b) -- ^ Function to do the conversion -> a -- ^ Input data -> ConvertResult b -- ^ Result @@ -70,3 +72,23 @@ convertVia :: (Convertible a b, Convertible b c) => convertVia dummy inp = do r1 <- safeConvert inp safeConvert (asTypeOf r1 dummy) + +{- | Make an intermediary conversion based on a function (a -> Maybe b). For instance: + +>data Foo +>instance Show Foo where ... +> +>data Bar +instance Read Bar where ... +> +>instance Convertible Foo [Char] where ... +> +>instance Convertible Foo Bar where +> safeConvert = convertMay (strMsg "Invalid Bar") readMay + -} +convertMay :: Convertible a b => + ConvertError -- ^ Error if the conversion fails + -> (b -> Maybe c) -- ^ Conversion from intermediate type to end result + -> a -- ^ Input value + -> ConvertResult c -- ^ Result +convertMay e f = maybe (throwError e) return . f <=< safeConvert diff --git a/convertible.cabal b/convertible.cabal index 819f8a3..bc40316 100644 --- a/convertible.cabal +++ b/convertible.cabal @@ -12,6 +12,7 @@ extra-source-files: LICENSE, utils/genCinstances.hs, testsrc/TestNum.hs, testsrc/TestTime.hs homepage: http://hackage.haskell.org/cgi-bin/hackage-scripts/package/convertible +bug-reports: https://github.com/hdbc/convertible/issues Category: Data synopsis: Typeclasses and instances for converting between types Description: convertible provides a typeclass with a single function @@ -36,8 +37,10 @@ Description: convertible provides a typeclass with a single function on GHC and Hugs. Stability: Stable Build-Type: Simple - Cabal-Version: >=1.2 +source-repository head + type: git + location: https://github.com/hdbc/convertible.git flag splitBase description: Choose the new smaller, split-up base package. @@ -75,7 +78,7 @@ library Extensions: ExistentialQuantification, MultiParamTypeClasses, UndecidableInstances, FlexibleInstances, FlexibleContexts, TypeSynonymInstances, CPP - + Executable runtests if flag(buildtests) Buildable: True