On 12 December 2012 21:57, Navid Hallajian <navi...@gmail.com> wrote:
> Hello,
>
> I'm a beginner in Haskell, so forgive me if this is a basic question, but
> I'd like to know if it's possible to have a predicate as part of a data
> type, so that when the data type is created, it can only be done if it
> satisfies the predicate else a type error is thrown.
>
> For instance, a matrix with integer elements could be modelled as [[Int]],
> given the restrictions that
>
> it must have at least one column and one row (so there must be at least one
> list), and
> every list must have the same length
>
> so that when a matrix is created, the type system wont allow it if the
> predicates aren't met.

Write a custom constructor function that returns a Maybe:

newtype Matrix = Matrix [[Int]]

makeMatrix :: [[Int]] -> Maybe Matrix
makeMatrix [] = Nothing -- No columns
makeMatrix [[]] = Nothing -- Has a column but no rows
...

It is possible with smarter types to encode various predicates into
the actual type, but for your purposes they probably aren't required.

>
> Thanks,
>
> Navid
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe@haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>



-- 
Ivan Lazar Miljenovic
ivan.miljeno...@gmail.com
http://IvanMiljenovic.wordpress.com

_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to