Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic type constructor for a type synonym

Tags:

haskell

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?

like image 495
Maik Klein Avatar asked Dec 16 '22 03:12

Maik Klein


1 Answers

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.

like image 179
n. 1.8e9-where's-my-share m. Avatar answered Dec 17 '22 18:12

n. 1.8e9-where's-my-share m.