Does anyone know what's the meaning of the ':>' constructor in the following code:
data Rose a = a :> [Rose a]
deriving (Eq, Show)
A data constructor is a "function" that takes 0 or more values and gives you back a new value. A type constructor is a "function" that takes 0 or more types and gives you back a new type.
Allow the use and definition of types with operator names. The language TypeOperators allows you to use infix operators in types. Operator symbols are constructors rather than type variables (as they are in terms).
Data constructors are first class values in Haskell and actually have a type. For instance, the type of the Left constructor of the Either data type is: Left :: a -> Either a b. As first class values, they may be passed to functions, held in a list, be data elements of other algebraic data types and so forth.
In Haskell the functions whose name consists of alphanumeric characters are prefix by default, and the functions made up from characters like +
, >
, $
etc are infix by default. For example, you can define an infix function like
Prelude> let a $%^ b = a + b
Prelude> :t ($%^)
($%^) :: Num a => a -> a -> a
Same applies to constructors (Edit: as @ChrisTaylor correctly noted, with the limitation that the name of an infix constructor must start with :
). The line
Prelude> data Rose a = a :> [Rose a]
Means that :>
is a constructor that takes two arguments:
Prelude> :t (:>)
(:>) :: a -> [Rose a] -> Rose a
You could as well create a normal-looking constructor as
data Rose a = RoseCtr a [Rose a]
which would have the same type. In some cases infix functions/constructors are more intuitive and make the code more understandable.
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