Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between an Int and a Maybe Int in Haskell?

Tags:

int

haskell

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?

like image 445
Eddie Avatar asked Jan 12 '23 04:01

Eddie


2 Answers

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.

like image 159
jev Avatar answered Jan 20 '23 01:01

jev


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`
like image 38
bheklilr Avatar answered Jan 20 '23 03:01

bheklilr