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!
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.
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.
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'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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With