I am going through some Haskell documentation, and found the statement
You can declare a constructor (for both type and data) to be an infix operator, and this can make your code a lot more readable.
I am able to use data constructor in infix form like below:
Prelude> data List a = Empty | a :-> (List a) deriving Show
Prelude>
Prelude> let var1 = 10 :-> Empty
Prelude> let var2 = 20 :-> var1
Prelude> let var3 = 30 :-> var2
Prelude>
Prelude> var1
10 :-> Empty
Prelude>
Prelude> var2
20 :-> (10 :-> Empty)
Prelude>
Prelude> var3
30 :-> (20 :-> (10 :-> Empty))
My question is how to use type constructor in infix form, Can somebody give me an example to understand this ?
> :set -XTypeOperators
> data a :-> b = C (a -> b)
> :t C id
C id :: b :-> b
Remember that its name must start with (No longer needed -- see the answer by Cactus for more information):
(roughly, :
is considered "uppercase").
Otherwise, use backticks, as in a `T` b
.
To expand on @chi's answer, with recent GHC versions, the syntax of TypeOperators
has changed somewhat: type constructor names that would otherwise be infix type variable names (i.e. symbols without a leading :
) are still classified as type constructor names, meaning the following code works and defines an infix type constructor +
:
{-# language TypeOperators #-}
data a + b = L a | R b
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