I don't understand why I get the following response from GHCi. Isn't Maybe
a constructor function?
Prelude> :t Maybe
<interactive>:1:1: Not in scope: data constructor `Maybe'
Prelude> let e = Maybe 5
<interactive>:1:9: Not in scope: data constructor `Maybe'
Among major programming languages, there are probably none that feel scarier for beginners than Haskell. And some years ago, it was so for a reason.
Yes, Haskell is worth learning in 2022 because functional languages like it are getting more popular among big companies like Facebook. Functional languages are typically ideal for big data and machine learning.
Haskell is considered a very hard language to learn and master. On the other hand, Python is considered the easiest and most useful programming language to use.
Start Haskell If you have installed the Haskell Platform, open a terminal and type ghci (the name of the executable of the GHC interpreter) at the command prompt. Alternatively, if you are on Windows, you may choose WinGHCi in the Start menu. And you are presented with a prompt.
Maybe
is a type constructor, and its two possible data constructors are Nothing
and Just
. So you have to say Just 5
instead of Maybe 5
.
> let x = Just 5
> x
Just 5
> let y = Nothing
> y
Nothing
> :type x
x :: Maybe Integer
> :type y
y :: Maybe a
> :info Maybe
data Maybe a = Nothing | Just a -- Defined in Data.Maybe
instance Eq a => Eq (Maybe a) -- Defined in Data.Maybe
instance Monad Maybe -- Defined in Data.Maybe
instance Functor Maybe -- Defined in Data.Maybe
instance Ord a => Ord (Maybe a) -- Defined in Data.Maybe
instance Read a => Read (Maybe a) -- Defined in GHC.Read
instance Show a => Show (Maybe a) -- Defined in GHC.Show
Maybe
is a type constructor because it is used to construct new types (the result type depends on the type of a
in Maybe a
), where such a type might be Maybe Int
(notice, there's no type param a
anymore, i.e. all type parameters are bound). Just a
and Nothing
are data constructors because they're used to construct instances of a certain Maybe
type, for example Just Int
creates instances of Maybe Int
.
Another major difference is that you can only use data constructors when pattern matching. You can't say:
case foo of
Maybe a -> ...
You'll have to say:
case foo of
Just a -> ...
Nothing -> ...
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