[Haskell-beginners] Alternative instance w/ additional restriction

Baa aquagnu at gmail.com
Wed Jun 7 12:26:44 UTC 2017


Hello all!

If I try to write, for example:

  instance Alternative MyData where
    empty = NoMyData
    a <|> b = if a == b then ...

I get error (see on bottom of the mail) sure, bcz I suppose something
like:

   Eq a => (MyData a)

All my attempts to add something to instance's `pure` signature have
failed. How can I instantiate something with additional restrictions,
like in this case? Or are there another solutions for such problem?

Interesting is that MyData derives Eq itself! Which, I suppose, must
means that "Eq (MyData a)", and if it's true than "Eq a" is true,
because how "MyData a" can be Eq without to be "Eq a" (with
*automatically deriving* of Eq instance) ?!

By the way, for Monoid (which is "* -> Constraint") I can add "Eq a"
constraint without problems:

  instance Eq a => Monoid (Origin a) where
    mempty = NoMyData
    mappend NoMyData a = a
    mappend a NoMyData = a
    mappend (MyData a) (MyData b)|a == b = MyData a
                                 |otherwise = NoMyData

but not for Alternative, which is "(* -> *) -> Constraint".

*ORIGINAL ERROR DUMP*:
======================
    42  16 error           error:                                                                                                       
                               • No instance for (Eq a) arising from a use of ‘==’                                                      
                                 Possible fix:                                                                                          
                                   add (Eq a) to the context of                                                                         
                                     the type signature for:                                                                            
                                       (<|>) :: Origin a -> Origin a -> Origin a                                                        
                               • In the expression: a == b                                                                              
                                 In the expression: if a == b then NoOrigin else NoOrigin                                               
                                 In an equation for ‘<|>’:                                                                              
                                     a <|> b = if a == b then NoOrigin
                                     else NoOrigin (intero)


/Best regards
  Paul


More information about the Beginners mailing list