[Haskell-cafe] "Casting" newtype to base type?

Vlatko Basic vlatko.basic at gmail.com
Mon Jul 1 17:07:00 CEST 2013


Hello Cafe!

I had a (simplified) record

   data P = P {
     a :: String,
     b :: String,
     c :: IO String
     } deriving (Show, Eq)

but to get automatic deriving of 'Show' and 'Eq' for 'data P' I have created 
'newtype IOS' and its 'Show' and 'Eq' instances

   newtype IOS = IO String
   instance Show (IOS) where show _ = "(IO String) function"
   instance Eq   (IOS) where _ == _ = True

(the easiest 'instance Show (IO String) where ...' produces "orphan instance")

and changed 'data P' to

   data P = P {
     a :: String,
     b :: String,
     c :: IOS
     } deriving (Show, Eq)

but now when I try to set 'c' field in

   fun :: FilePath -> P -> IO P
   fun path p = do
     b <- doesFileExist path
     ...
     return $ p {c = readFile path}

I get error
   Couldn't match expected type `IOS' with actual type `IO String'

which is correct.

So, the question is:

   Is it possible to somehow "cast" 'IO String' to 'IOS',
   or in some other way set 'c' field to an 'IO String' function
   so that it can be later used such as 'content <- c p'.



Thanks



More information about the Haskell-Cafe mailing list