Super simple I'm sure, but I can't seem to find the answer. I call a function that returns Maybe x
and I want to see x
. How to I extract x
from my Just x
response?
seeMyVal :: IO ()
seeMyVal = do
if getVal == Nothing
then do
putStrLn "Nothing to see here"
else do
putStrLn getVal -- what do I have to change in this line?
getVal :: (Maybe String)
getVal = Just "Yes, I'm real!"
This throws the error:
Couldn't match type ‘Maybe String’ with ‘[Char]’
Expected type: String
Actual type: Maybe String
In the first argument of ‘putStrLn’, namely ‘getVal’
In a stmt of a 'do' block: putStrLn getVal
The idiomatic way is to pattern match.
seeMyVal = case getVal of
Nothing -> putStrLn "Nothing to see here"
Just val -> putStrLn val
If you like, you can factor the putStrLn
out:
seeMyVal = putStrLn $ case getVal of
Nothing -> "Nothing to see here"
Just val -> val
You can also use fromMaybe, which takes a default.
fromMaybe "Nothing to see here..." (Just "I'm real!")
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