Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell beginner

Tags:

haskell

maybe

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'
like image 695
David Kramf Avatar asked Oct 30 '11 20:10

David Kramf


People also ask

Is Haskell good for beginners?

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.

Is Haskell Worth learning 2022?

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.

Is Haskell harder than Python?

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.

How do I get started with Haskell?

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.


1 Answers

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 -> ...
like image 114
Ionuț G. Stan Avatar answered Oct 15 '22 22:10

Ionuț G. Stan