Maik Klein
Maik Klein

Reputation: 16148

Automatic type constructor for a type synonym

I have a type called Vec2F and I can use it like this Vec2F 0.0 0.0. But I want to make my own type

type Direction = Vec2F

But then I can't do Direction 0.0 0.0 and I have to define a new function which is a little bit cumbersome.

direction :: Float -> Float -> Vec2F
direction = Vec2F

What alternatives do I have?

Upvotes: 4

Views: 673

Answers (2)

n. m. could be an AI
n. m. could be an AI

Reputation: 119867

I have a type called Vec2F and I can use it like this Vec2F 0.0 0.0

No you cannot.

What you actually have is a data definition

data Vec2F = Vec2F Double Double

It's the second Vec2f you can use in expressions. These two occurrences of Vec2F are invisible to each other. They live in separate namespaces. One is a type constructor and the other is a data constructor.

You can have definitions like

data Foo = Bar Double
data Bar = Foo Float

and the language will swallow it (as opposed to the human reader).

When you define a type synonym, it only becomes a synonym for the type (constructor). It knows nothing about the data constructor.

There's no way to define a data constructor synonym in standard Haskell. You probably can use view patterns [-XViewPatterns] to a similar effect. I have not tried them.

Upvotes: 10

gspr
gspr

Reputation: 11227

One option is

newtype Direction = Direction Vec2F

You'd then create Directions like Direction (Vec2F 0.0 0.0). Note that now Direction and Vec2F are distinct types, whereas they would be synonymous if you had used type Direction = Vec2F.

Upvotes: 2

Related Questions