Akshat Goel
Akshat Goel

Reputation: 528

How to get output of function returning Maybe?

This is a newbie question.

I am having a trouble understanding the output of StripPrefix function which returns Maybe [a].

What I am doing is, I am passing two strings to StripPrefix so that it gives back the string after cutting the prefix.

What I have tried is :

let b = stripPrefix pref stri

Just b <- stripPrefix pref stri

In first case, my print operation (putStrLn b) throws error "Couldn't match type Maybe [Char]' with[Char]'"

Upvotes: 0

Views: 1231

Answers (2)

bheklilr
bheklilr

Reputation: 54068

From the comments on the question:

In GHCi, if you want to extract the a from a Maybe a you have a few options. First, if you're sure it will succeed with a Just something, you can do

> let Just a = Just 1
> print a
1

However, this can lead to problems if your operation is not successful

> let Just a = Nothing :: Maybe Int
> print a
*** Exception <interactive>12:5-20: Irrefutable pattern failed for pattern Data.Maybe.Just a

All this is saying is that the pattern matching you used failed. How do we avoid this? There's case statements:

> -- Enable multiline input (I have this in my .ghci file so it's always on)
> :set +m
> let maybeA = Just 1
|
> case maybeA of
|    Just x -> print x
|    Nothing -> return ()    -- Do nothing
|
1

But this is laborious. Wouldn't it be nice if there was an alternative built-in to Haskell? Fortunately, there is in the Data.Maybe module:

> import Data.Maybe
> :type maybe
maybe :: b -> (a -> b) -> Maybe a -> b
> -- The -1 is our default value in case of Nothing
> print $ maybe (-1) id $ Just 1
1
> print $ maybe (-1) id $ Nothing
-1

There's even an easier function to use when all you want is either the value in a Just or a default value:

> print $ fromMaybe (-1) $ Just 1
1

But maybe is more powerful in general:

> print $ maybe 0 (\x -> 2 * x - x * x * x + 7 ^ x) $ Just 3
322

There are still times, though, that all you want to know is if an operation was successful. For that, Data.Maybe has isJust and isNothing:

> isJust $ Just 1
True
> isJust $ Nothing
False

And isNothing = not . isJust, obviously.

Upvotes: 3

Benjamin Kovach
Benjamin Kovach

Reputation: 3260

That's because putStrLn :: String -> IO () and b :: Maybe String. putStrLn expects its first argument to be a String, and that's not what b is. You can use print :: Show a => a -> IO () to print a Maybe value, provided that the type it contains is itself Showable.

Upvotes: 1

Related Questions