Haskell instance is read for newtype, which is just int

I am new to Haskell and I want to be able to have a new type so that I can understand what it is, but I also need to read it from a line. I have

newtype SpecialId Int
    deriving (Eq, Ord, Show)

I want to be able to read "5" :: SpecialId, if I get Read in newtype, it does not work, it only works on read "SpecialId 5" :: SpecialId. I tried

instance Read SpecialId where
    readsPrec _ s = read s

But it gives me

SpecialId *** Exception: Prelude.read: no parse
+4
source share
2 answers

This is possible since GHC 8.2 using -XDerivingStrategies:

{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DerivingStrategies         #-}

newtype SpecialId = SpecialId Int
    deriving stock   (Eq, Ord, Show)
    deriving newtype Read

In ghci:

ghci> read "5" :: SpecialId 
SpecialId 5
+9
source

You do not need a language extension if you are ready to send the instance Intmanually:

instance Read SpecialId where
    readsPrec n s = [ (SpecialId x, y) | (x, y) <- readsPrec n s ]

, readsPrec: Int readsPrec, (Int, String), , Int SpecialId.

+6

Source: https://habr.com/ru/post/1688597/


All Articles