Martin Hofmann | 13 Oct 17:23
Favicon

Associated Types and several Classes

> {-# OPTIONS_GHC -fglasgow-exts #-}
> module Test where
>import qualified Data.Set as S

Hi. I try to model the following: Hypotheses are build up from Rules, 
which itself are made of the type Rule. Because I may change the 
implementation later, I want to use type classes, which define the
signature of my functions I will use in other modules. 

>class CRule r 

>class (CRule (CRulesRule r) ) => CRules r where
>    type CRulesRule r

>class (CRule (CHypoRule h), CRules (CHypoRules h) ) => CHypo h where
>    type CHypoRules h
>    type CHypoRule h
>    hypo ::  
>        CHypoRules h ->     
>        CHypoRule h ->      
>        h                   

-- | Rule

>data Rule = Rule Int deriving(Eq,Ord)
>instance CRule Rule 

-- | Rules

>type Rules = S.Set Rule
(Continue reading)

Ryan Ingram | 13 Oct 19:10

Re: Associated Types and several Classes

First, a comment.  I don't understand why you have so many classes!
What proof invariants are they helping you enforce?  Do you really a
constraint that says that something is a "Rule"?  Are you going to
write functions that are polymorphic over CRule?  How can you do so
when CRule has no methods?

Now, to the explanation.  You're partially running into the
monomorphism restriction here, but that's not the whole story.

If you comment out ahypo, this module compiles.  Then, in ghci:

*Test> :t hypo rules rule1
hypo rules rule1 :: (S.Set Rule ~ CHypoRules h, Rule ~ CHypoRule h, CHypo h) =>
                    h

So the reason you are failing to compile is that "ahypo", as a plain
value, needs to have a monomorphic type, so we need to figure out how
to instantiate "h".  In the absence of other information, the compiler
can't figure out what to select for "h"; I'm free to come by after the
fact and define a new instance for CHypo over another data type that
has CHypoRules = S.Set Rule, and CHypoRule = Rule, and then ahypo
could be either type.

It's possible that the compiler should be extended to "default" in the
case that only one possible type is in scope (although that search
might be tricky!), but right now it just gives up because it can't
choose an "h".

You can turn this off with "-fno-monomorphism-restriction", but I
don't really recommend that.  Instead, here are some suggestions, in
(Continue reading)

Martin Hofmann | 14 Oct 08:57
Favicon

Re: Associated Types and several Classes

Hi Ryan.

Thanks a lot, that was exactly the information I needed.

Concerning the type classes, there are methods, but I dropped them,
because they were not necessary for the problem. However, you are right.
Implementation hiding is what I need.

One suggestion. Maybe a HaskellWiki page on design patterns with best
practises would be helpful. So which problem to solve how and which
technique (type classes, type families, ...)is useful for what. Or is
there already something like this?

Thanks again,

Martin

Gmane