'Defining new types in Haskell
I am pretty new to Haskell, and I was wondering if one can define new types that are defined by lists of other types. For example, I assume a string is defined as a list of characters, so can I define a vector as a list of force values (in this case floating point values)?
If so, how can I declare and use this?
data Vector = Vector [Float]
Is this enough to define the new type and the constructor for it? Can I simply call
x = Vector [2.4,2.5,2.7]
for example?
I'm using ghci, if that makes any difference
Solution 1:[1]
Yes - data TypeName = TypeConstructor Type1 Type2 ... TypeN
just creates a function TypeConstructor :: Type1 -> Type2 -> ... -> TypeN -> TypeName
, and there is special syntactic sugar for lists so that what would normally have to be something like List Float
to instead be [Float]
.
So data Vector = Vector [Float]
creates a function Vector :: [Float] -> Vector
(note that the function and the result type are different things that happen to share a name).
The Vector
function is called a type constructor, and type constructors are the only functions that can have initial capital letters in their name.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Micha Wiedenmann |