Is there a difference between an Int
and a Maybe Int
in Haskell? And if there is, how do I convert a Maybe Int
to an Int
?
Yes, they are of different types: there is Maybe Int
could be Nothing
or Just Int
, where Int
is always Int
.
Maybe is defined in Data.Maybe
as
data Maybe a = Just a | Nothing
deriving (Eq, Ord)
and should be used if a function may not return a valid value. Have a look at functions isJust
, isNothing
, and fromJust
(use Hoogle, the Haskell API search engine).
Inside your function you can e.g.
case maybeValue of
Just x -> ... -- use x as value
Nothing -> ... -- erroneous case
Alternatively, use fromMaybe
(also from Data.Maybe
) which takes a default value and a Maybe
and returns the default value if the Maybe
is a Nothing
, or the actual value otherwise.
The Maybe
data type represents a value that can be null, and is usually used as the return value from a function that can either succeed with just a value, or fail with no value. It has two constructors: Nothing
and Just a
, where a
is whatever value you're returning. You can use it like this:
safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead (x:xs) = Just x
You can extract the value using pattern matching, or using a handful of functions from Data.Maybe
. I usually prefer the former, so something like:
main = do
let xs :: [Int]
xs = someComputation 1 2 3
xHead = safeHead xs
case xHead of
Nothing -> putStrLn "someComputation returned an empty list!"
Just h -> putStrLn $ "The first value is " ++ show h
-- Here `h` in an `Int`, `xHead` is a `Maybe Int`
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