Reputation: 891
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
?
Upvotes: 4
Views: 2281
Reputation: 2013
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.
Upvotes: 6
Reputation: 54068
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`
Upvotes: 3