Saturday 30 April 2016

Haskell: Declare constructor to be an infix operator


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. Name of an infix constructor must start with : and preceded by non-alphanumeric characters like +, -, * etc., where as an infix function starts with any other symbol.
data List a = Empty | a :-> (List a) deriving Show


Above statement defines a data constructor :->, you can query for the signature of data constructor.
Prelude> :t (:->)
(:->) :: a -> List a -> List a

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))
 
How to use type constructor in infix form?
To use type constructor in infix form, you should enable GHC TypeOperators extension.
Prelude> :set -XTypeOperators
Prelude> 
Prelude> data a :-> b = C (a -> b)
Prelude> 
Prelude> :t C id
C id :: b :-> b


With latest GHC versions, type constructor name need not to be followed by : in infix form.
Prelude> :set -XTypeOperators
Prelude> data a +++ b = C (a -> b)


Reference

 
Previous                                                 Next                                                 Home

No comments:

Post a Comment