0

Suppose, I have this function which accepts a Maybe arg:

func1 :: Maybe Int -> Int
func1 mbArg = 
  let var1 = case myArg of
               Just x -> x
               Nothing -> -1
  -- ....

I wonder, is there any other way to do the same thing but using something like mapM, mapM_ or fmap or <$> or anything similar? That is, check if it's Just or Nothing and extract the real value or return the default value respectively.

My question is about Maybe as a Monad.

  • 1
    You can use `fromMaybe` or `maybe` for this purpose. See http://stackoverflow.com/questions/3375483/operating-on-a-return-from-a-maybe-that-contains-just – Thomas M. DuBuisson Apr 13 '16 at 15:02
  • @ThomasM.DuBuisson, from a Monad. –  Apr 13 '16 at 15:02
  • That doesn't change my understanding of the question. You have a `value :: Maybe a` and a function of type `a -> Maybe b` and wish to use them in a monadic style? If that's true then `value >>= function`. That is, the bind operator is what you want, `do v <- value; function v` – Thomas M. DuBuisson Apr 13 '16 at 15:05
  • 1
    for general extracting values from monads, you may take a look at http://stackoverflow.com/questions/8567743/how-to-extract-value-from-monadic-action – Tomasz Lewowski Apr 13 '16 at 15:06

0 Answers0