Parsing error in case expression

I am trying to convert Maybe Int to 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 item in a list using the elem.Index function from the Data.List module, and then use that index for the take function. My problem is what elemIndex

returns Maybe Int

, but take

is required Int

.

+3


source to share


2 answers


This is a problem with spaces. Classes case

must be indented one level.

convert :: Maybe Int -> Int
convert mx = case mx of 
               Just x -> x
               Nothing -> error "error message"

      



Remember to only use spaces, no tabs.

+6


source


To add to @leftaroundabout's answer, I think I can provide you with other options.

First, you shouldn't do such unsafe things: your program will fail. It's much cleaner to keep it like that Maybe Int

and act as such, safe. In other words, it was a simple parsing error, but doing such incomplete functions could lead to much bigger problems in the future.

The problem you are facing, how can I do this?

We can make a better function like:

mapMaybe :: (a -> b) -> Maybe a -> Maybe b
mapMaybe f m = case m of
     Just a  -> f a
     Nothing -> Nothing

      

What could you write:



λ> (+ 15) `mapMaybe` Just 9
Just 24

      

However, there is a function called fmap

that "maps" a function over certain data structures, including Maybe

:

λ> (== 32) `fmap` Just 9
Just False

      

and if you have import

ed Control.Applicative

there is a syntax synonym for it:

λ> show <$> Just 9
Just "9"

      

If you want to learn more about these data structures called functors, I would recommend reading Learn-you the Haskell .

+2


source







All Articles