Trident D'Gao
Trident D'Gao

Reputation: 19690

Is data constructor a function?

I found the following example here

instance Monad Maybe where
    Nothing  >>= f = Nothing
    (Just x) >>= f = f x
    return         = Just

The return method is defined in the pointfree style, which I know is applicable to functions, but here we have a data constructor whose declaration syntax looks different from the one of functions let alone its purpose.

Another tutorial says:

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 :: forall b a. 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.

So can anyone make it clear what data constructors are and how they are different from functions if anything.

Upvotes: 1

Views: 424

Answers (2)

viorior
viorior

Reputation: 1803

Data constructor is just a function with eta-reduction:

Just === \x -> Just x

Left === \x -> Left x

But Nothing is a function without arguments

Upvotes: 1

Sarah
Sarah

Reputation: 6695

One specific difference, at least, is that data (value) constructors can be used in pattern matches while functions that are not data constructors cannot. It is the only real difference I can think of, other than the fact that "nullary" data constructors (think Nothing) are, well, nullary.

Upvotes: 7

Related Questions