[Haskell-beginners] How to avoid repeating a type restriction from a data constructor

Daniel Fischer daniel.is.fischer at googlemail.com
Tue Apr 23 17:31:59 CEST 2013


On Tuesday 23 April 2013, 15:05:05, gs wrote:
> In
> http://code.accursoft.com/binding/src/c13ccbbec0ba8e326369ff2252863f20a891ef
> 76/binding-core/src/Data/Binding/Simple.hs there's a data constructor
>     data Source v a = Variable v => Source {bindings :: v [Binding a], var
> 
> :: v a}
> 
> Source is used many times in this file and in
> http://code.accursoft.com/binding/src/c13ccbbec0ba8e326369ff2252863f20a891ef
> 76/binding-core/src/Data/Binding/List.hs, and each time, I have to repeat
> the context Variable v. Is there any way to avoid this redundancy?
> 

Use a GADT,

{-# LANGUAGE GADTs #-}

data Source x y where
    Source :: Variable v => { bindings :: v [Binding a], var :: v a }
                     -> Source v a

The `Variable v` context becomes available by pattern-matching on the 
constructor `Source` (but not by using the field names to deconstruct a value 
of type `Source v a`!). With the original datatype context, that wasn't so 
(thus datatype contexts were mostly unhelpful; they have been removed from the 
language, and now require the DatatypeContexts extension in GHC).

If you can't change the definition of the datatype, you can't avoid the 
redundancy, you have to mention the `Variable v` context everywhere Source is 
used (unless you omit type signatures altogether).



More information about the Beginners mailing list