Extract x from (Just x) in Maybe

Super simple, I'm sure, but I can not find the answer. I call a function that returns Maybe xand I want to see x. How to extract xfrom my answer Just x?

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 causes an 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
+4
source share
3 answers

There is a standard feature with this signature fromJust.

Use Hoogle for searches like this, this is a great tool .

+2
source

The idiomatic way is pattern matching.

seeMyVal = case getVal of
    Nothing  -> putStrLn "Nothing to see here"
    Just val -> putStrLn val

If you like, you can point putStrLnout:

seeMyVal = putStrLn $ case getVal of
    Nothing  -> "Nothing to see here"
    Just val -> val
+19
source

fromMaybe, .

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

+9
source

Source: https://habr.com/ru/post/1616317/


All Articles