Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write a derivable class?

Tags:

haskell

i have this

data Something = Something Integer deriving (MyClass, Show)

class MyClass a where   
    hello :: MyClass a => a -> a

instance MyClass Integer where
    hello i = i + 1

main = print . hello $ Something 3

but MyClass isn't derivable. Why?

like image 529
Vektorweg Avatar asked Feb 07 '13 16:02

Vektorweg


2 Answers

GHC cannot magically derive instances for arbitrary data types. However, it can make use of the fact that newtype declarations create a new name for the same underlying type to derive instances for those using the GeneralizedNewtypeDeriving extension. So, you could do something like this:

{-# LANGUAGE GeneralizedNewtypeDeriving #-}

newtype Something = Something Integer deriving (MyClass, Show)

class MyClass a where
    hello :: MyClass a => a -> a

instance MyClass Integer where
    hello i = i + 1

main = print . hello $ Something 3

The reason GHC cannot derive the new instance is that it does not know what the instance should be. Even if your data type only has one field, it may not necessarily be the same as that field. The ability to derive instances for newtypes is convenient, since they are usually used to provide different behaviours for certain typeclasses or as a way to use the type system to separate things that have the same type but different uses in your code.

like image 89
sabauma Avatar answered Sep 27 '22 02:09

sabauma


You may want to have a look at the GHC documentation on Generic Programming.
You need to create a class that can work on a generic representation of arbitrary types. I don't think the specific example you gave is reasonable for a derivable class.

like image 36
asm Avatar answered Sep 27 '22 02:09

asm