I am trying to convert a Maybe Int to an Int in Haskell like this:
convert :: Maybe Int -> Int
convert mx = case mx of
Just x -> x
Nothing -> error "error message"
When I compile it, Haskell tells me: parse error on input 'Nothing'
.
I need this, because I want to get the Index of an element in a list with the elem.Index function from the Data.List module and then use this index on the take function. My problem is that elemIndex
returns a Maybe Int
, but take
needs an Int
.
Just
, but the type checker can't proove it. And even then it's better to explicitly matchcase mx of {Just x -> x}
right where you need it, not through a helper function. The reason being: if this match does fail, it will give you a nice clear error message telling where it happened. Yourconvert
will always give you the same error message when the assumption fails, no matter where you use it. – VolcanismtakeWhile (/= item)
? – Karlee