Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting x from (Just x) in a Maybe [duplicate]

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
like image 863
Mark Karavan Avatar asked Nov 28 '22 05:11

Mark Karavan


2 Answers

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
like image 119
Daniel Wagner Avatar answered Dec 04 '22 10:12

Daniel Wagner


You can also use fromMaybe, which takes a default.

fromMaybe "Nothing to see here..." (Just "I'm real!")

like image 38
robertjflong Avatar answered Dec 04 '22 12:12

robertjflong