Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Deriving Show for custom type

I have this type definition:

data Operace = Op (Int->Int->Int) String (Int->Int->Int) deriving Show 

I want to print this type into the interactive shell (GHCi). All that should be printed is the String field.

I tried this:

instance Show Operace where     show (Op op str inv) = show str 

But I still keep getting

No instance for (Show (Int -> Int -> Int))   arising from the 'deriving' clause of a data type declaration Possible fix:   add an instance declaration for (Show (Int -> Int -> Int))   or use a standalone 'deriving instance' declaration,        so you can specify the instance context yourself When deriving the instance for (Show Operace) 

I don't want to add Show for (Int->Int->Int), all I want to print is the string.

Thanks for help!

EDIT:

For future reference, the fixed version is:

data Operace = Op (Int->Int->Int) String (Int->Int->Int)  instance Show Operace where     show (Op _ str _) = str 
like image 376
Matěj Zábský Avatar asked May 21 '11 13:05

Matěj Zábský


People also ask

What does deriving show do in Haskell?

The second line, deriving (Eq, Show) , is called the deriving clause; it specifies that we want the compiler to automatically generate instances of the Eq and Show classes for our Pair type. The Haskell Report defines a handful of classes for which instances can be automatically generated.

How do you define Typeclass in Haskell?

What's a typeclass in Haskell? A typeclass defines a set of methods that is shared across multiple types. For a type to belong to a typeclass, it needs to implement the methods of that typeclass. These implementations are ad-hoc: methods can have different implementations for different types.

How are datatype in Haskell defined and created?

Haskell has three basic ways to declare a new type: The data declaration, which defines new data types. The type declaration for type synonyms, that is, alternative names for existing types. The newtype declaration, which defines new data types equivalent to existing ones.

How do you use EQ in Haskell?

The Eq typeclass provides an interface for testing for equality. Any type where it makes >sense to test for equality between two values of that type should be a member of the Eq >class. All standard Haskell types except for IO (the type for dealing with input and >output) and functions are a part of the Eq typeclass."


2 Answers

The instance declaration you made is the correct way to go. It seems you forgot to remove that faulty deriving clause from the original data declaration.

data Operace = Op (Int->Int->Int) String (Int->Int->Int)  instance Show Operace where    show (Op op str inv) = show str 
like image 86
hugomg Avatar answered Nov 09 '22 02:11

hugomg


You can derive Show, just import Text.Show.Functions first.

like image 44
Thomas M. DuBuisson Avatar answered Nov 09 '22 04:11

Thomas M. DuBuisson