Hari Krishna
Hari Krishna

Reputation: 3548

How to use type constructor in infix form

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 ?

Upvotes: 7

Views: 254

Answers (2)

chi
chi

Reputation: 116139

> :set -XTypeOperators
> data a :-> b = C (a -> b)
> :t C id
C id :: b :-> b

Remember that its name must start with : (roughly, : is considered "uppercase"). (No longer needed -- see the answer by Cactus for more information)

Otherwise, use backticks, as in a `T` b.

Upvotes: 8

Cactus
Cactus

Reputation: 27626

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

Upvotes: 5

Related Questions