McBear Holden
McBear Holden

Reputation: 5901

Haskell maybe function bewilderment

maybe :: b -> (a -> b) -> Maybe a -> b  -- Defined in `Data.Maybe'

From this definition of maybe, b can be any type and should be the same type as the return value of the function (a-> b) But when i tried this in Winghci:

maybe (error "no") (head) (Just "hi")
'h'
maybe (error "no") (return) (Just "hi")
"hi"

Both works but clearly return and head has different types and yet both work with (error "no") When I type:

:t error "no"

I get

error "no" :: a

Does this mean error "no" can be any type ? Why so ?

Upvotes: 3

Views: 832

Answers (1)

chamini2
chamini2

Reputation: 2918

> :t error
error :: [Char] -> a

error takes a String so you can inform the user what problem was.

As it returning a, it's because errors can happen anywhere in a program, so if it is "any type" you can set an error anywhere you need to.

For example:

the function head has the signature

head :: [a] -> a

it obviously returns the head of a list.

but what happens if we give to it an empty list.

Prelude> head ([] :: [Int])
*** Exception: Prelude.head: empty list

head was supposed to return a type Int because we forced it in the empty list

Prelude> :t head ([] :: [Int])
head ([] :: [Int]) :: Int

So what can we return that is type Int (for this particular case) and shows the user that something went wrong?

error "empty list"

but we need it to be Int, so error, as being a, can be anything, such as Int

The source code for head is like this:

head :: [a] -> a
head (x:_) = x
head []    = error "empty list"

Upvotes: 4

Related Questions