Duplicate instances when choosing a transition to one side of a tuple

I want to do something like this:

data MyDataType = MyDataType class HasSpecialField a where specialField :: a -> ByteString instance HasSpecialField a => HasSpecialField (a, b) where specialField (a, b) = specialField a instance HasSpecialField b => HasSpecialField (a, b) where specialField (a, b) = specialField b instance HasSpecialField MyDataType where specialField _ = "Coolio" 

That is, if you have a tuple like:

 myTuple :: (String, (Int, MyDataType)) 

Then you can run specialField myTuple to return "Coolio".

Is there any way to do this?

+4
source share
1 answer

Data can be used to accomplish this, but does not limit the function to only those types that are successful, deferring a condition to the execution time.

 {-# LANGUAGE DeriveDataTypeable #-} import Control.Applicative import Data.Generics data MyDataType = MyDataType deriving (Typeable, Data) specialField :: Data a => a -> Maybe String specialField = fmap (\ MyDataType -> "Coolio") . something gfindtype 
+1
source

All Articles