I'm relatively new to Haskell and began to read "Real World Haskell".
I Just stumbled over the type Maybe and have a question about how to receive the actual value from a Just 1
for example.
I have written the following code:
combine a b c = (eliminate a, eliminate b, eliminate c) where eliminate (Just a) = a eliminate Nothing = 0
This works fine if I use:
combine (Just 1) Nothing (Just 2)
But if I change, for example, 1 to a String it doesn't work.
I think I know why: because eliminate
has to give back one type, which is, in this case, an Int
. But how can I change eliminate
to deal at least with Strings (or maybe with all kind of types)?
The Maybe type encapsulates an optional value. A value of type Maybe a either contains a value of type a (represented as Just a ), or it is empty (represented as Nothing ). Using Maybe is a good way to deal with errors or exceptional cases without resorting to drastic measures such as error .
It's merely an infix synonym for fmap , so you can write e.g. Prelude> (*2) <$> [1.. 3] [2,4,6] Prelude> show <$> Just 11 Just "11" Like most infix functions, it is not built-in syntax, just a function definition. But functors are such a fundamental tool that <$> is found pretty much everywhere.
It represents "computations that could fail to return a value". Just like with the fmap example, this lets you do a whole bunch of computations without having to explicitly check for errors after each step.
From the standard Prelude
,
maybe :: b -> (a -> b) -> Maybe a -> b maybe n _ Nothing = n maybe _ f (Just x) = f x
Given a default value, and a function, apply the function to the value in the Maybe
or return the default value.
Your eliminate
could be written maybe 0 id
, e.g. apply the identity function, or return 0.
From the standard Data.Maybe
,
fromJust :: Maybe a -> a fromJust Nothing = error "Maybe.fromJust: Nothing" fromJust (Just x) = x
This is a partial function (does not return a value for every input, as opposed to a total function, which does), but extracts the value when possible.
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