Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use type constructor in infix form

Tags:

syntax

haskell

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 ?

like image 605
Hari Krishna Avatar asked Apr 22 '16 22:04

Hari Krishna


2 Answers

> :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.

like image 89
chi Avatar answered Oct 19 '22 10:10

chi


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
like image 5
Cactus Avatar answered Oct 19 '22 10:10

Cactus