Defining new types in Haskell

187 Views Asked by At

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

1

There are 1 best solutions below

6
janet On

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.