Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guarantee that type families will derive certain classes

I have something like the following:

{-# LANGUAGE TypeFamilies #-}

class Configuration c where
    data Pig c
    data Cow c

    parsePig :: GenParser Char st (Pig c)
    parseCow :: GenParser Char st (Cow c)

data Farm c =
    { pigs :: [Pig c]
    , cows :: [Cow c]
    } deriving Show

This fails because of the deriving Show line. I don't know how to force all Configuration instances to ensure that their data Pig and data Cow implementations are all instances of Show.

I know I could make it have showPig and showCow methods and the write out the whole complex show instance, but in reality things are more complex than this and that would be quite a pain.

Is there an easy, elegant way to guarantee that type family instances are themselves instances of certain classes?

like image 645
So8res Avatar asked Sep 13 '12 18:09

So8res


People also ask

Are CSS classes inherited?

Rules given in later classes (or which are more specific) override. So the fourthclass in that example kind of prevails. Inheritance is not part of the CSS standard.

How does CSS inherit work?

Inheritance in CSS occurs when an inheritable property is not set on an element. It goes up in its parent chain to set the property value to its parent value. CSS properties such as height , width , border , margin , padding , etc. are not inherited.

How does deriving work 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 web browsers choose which CSS to use for an HTML element when the CSS rules contradict each other?

How do we know which one will be used? In CSS, styles sheets cascade by order of importance. If rules in different style sheets conflict with one another, the rule from the most important style sheet wins.


1 Answers

You can use StandaloneDeriving to specify the constraints manually just for the Show instance.

{-# LANGUAGE StandaloneDeriving, FlexibleContexts, UndecidableInstances #-}
deriving instance (Show (Pig c), Show (Cow c)) => Show (Farm c)

This will still let you have Configuration instances with Cow and Pig that don't implement Show, however, as long as you don't try to show them.

like image 144
hammar Avatar answered Jan 12 '23 07:01

hammar