[Haskell-cafe] A question about constraints

minh thu noteed at gmail.com
Thu Oct 2 05:59:15 EDT 2008


2008/10/2 jean-christophe mincke <jeanchristophe.mincke at gmail.com>:
> Hello,
>
> Given a type T, this type identifies a set of values and this set can be
> deduced from the structure of type T.
>
> i.e the type String  is the set of all possible lists of character whatever
> their length.
>
> This being said, I have the following question:
>
> Given a type T, how is it possible to further restrict its set of values?
> i.e, in the above case, how is it possible to define a type String2 whose
> elements are any list of characters  whose length is <= 5.
>
> I believe the best way to deal with that is to make String2 an  ADT. This
> allows the constraint (in this case, the length) to be checked but hides the
> structure of the type, thus limits the use of pattern matching (in this case
> I do not want to hide the implementation of the type, so the ADT is not used
> that way).
>
> If one wants to use pattern matching, then the module must provide a way to
> convert from String2 to a type whose constructors are visible (asString in
> this exemple)
>
> module A
> (
> String2
> ,mkString2
> ,asString
> )
> where
>
> import List
>
> data String2 =  String2 String
>
>
> mkString2 l = if (length l) <= 5 then String2 l
>                                  else error "length > 5"
>
> asString (String2 l) = l
>
> Btw, F# has found a nice solution to this problem, it allows the user to
> define an "active pattern", that is, a pattern to applies on ADT:
>
>
> http://blogs.msdn.com/dsyme/archive/2007/04/07/draft-paper-on-f-active-patterns.aspx
>
> Is there another way to address that problem in Haskell?

I believe several proposal have been made to extend the current
pattern matching mechanism.
The author of the Fonctional Graph Library (FGL) has made one for instance.
(Maybe see the proposals for Haskell')

With the current mechanism, he uses instead a function that is applied
in a case expression
(thus on the right hand side of the definition).

Cheers,
Thu


More information about the Haskell-Cafe mailing list