Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Custom types with conditions

Tags:

types

haskell

I'm a haskell newbie and I couldn't find an answer to this question.

Can we define types with conditions? For example, simple user-defined data type would be:

data MyList = MyList [a]

Can I somehow modify this code so MyList constructor can take only lists with even number of elements? Something like

data MyList = MyList [a] where (even (length a))

Thank you!

like image 549
Alex Avatar asked Jul 23 '10 09:07

Alex


People also ask

How do you declare types in Haskell?

Haskell has three basic ways to declare a new type: The data declaration, which defines new data types. The type declaration for type synonyms, that is, alternative names for existing types. The newtype declaration, which defines new data types equivalent to existing ones.

Can Haskell lists have different types?

Haskell also incorporates polymorphic types---types that are universally quantified in some way over all types. Polymorphic type expressions essentially describe families of types. For example, (forall a)[a] is the family of types consisting of, for every type a, the type of lists of a.

What is Newtype in Haskell?

In Haskell, the newtype declaration creates a new type from an existing one. For example, natural numbers can be represented by the type Integer using the following declaration: newtype Natural = MakeNatural Integer. This creates an entirely new type, Natural, whose only constructor contains a single Integer.

What is a Typeclass in Haskell?

What's a typeclass in Haskell? A typeclass defines a set of methods that is shared across multiple types. For a type to belong to a typeclass, it needs to implement the methods of that typeclass. These implementations are ad-hoc: methods can have different implementations for different types.


1 Answers

No, you can't.

If it's really necessary, just write a constructor-like function by yourself.

toMyList :: [a] -> MyList
toMyList l | even (length l) = MyList l
           | otherwise       = error "Length of list has to be even"

or if error-checking is likely to occur:

toMyList :: [a] -> Maybe MyList

But depending on the use-case, maybe you can express yourself through types (e.g. tuples or two lists) than through runtime-checks.

like image 164
Dario Avatar answered Oct 07 '22 08:10

Dario