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

Vlatko Basic vlatko.basic at gmail.com
Tue Jul 2 15:03:08 CEST 2013


Is there a nicer way to extract the 'IO String' from 'IOS',
without 'case' or without pattern matching the whole 'P'?

newtype IOS = IOS (IO String)
data P = P {
   getA :: String,
   getB :: String,
   getC :: IOS
   } deriving (Show, Eq)


getC_IO :: P -> IO String
getC_IO p =
   case getC p of
     IOS a -> a
getC_IO (P _ _ (IOS a)) = a



-------- Original Message  --------
Subject: Re: [Haskell-cafe] "Casting" newtype to base type?
From: Malcolm Wallace <malcolm.wallace at me.com>
To: vlatko.basic at gmail.com
Cc: Haskell-Cafe <haskell-cafe at haskell.org>
Date: 01.07.2013 17:24

>
> On 1 Jul 2013, at 16:07, Vlatko Basic wrote:
>
>> 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
>
> Not quite!  That is a newtype'd String, not a newtype's (IO String).  Try this:
>
>      newtype IOS = IOS (IO String)
>
>> but now when I try to set 'c' field in
>>
>>     return $ p {c = readFile path}
>>
>> I get error
>>   Couldn't match expected type `IOS' with actual type `IO String'
>
> Use the newtype constructor to convert an IO String -> IOS.
>
>      return $ p {c = IOS $ readFile path}
>
> Regards,
>      Malcolm
>



More information about the Haskell-Cafe mailing list