Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse error in a case statement

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.

like image 923
imc Avatar asked Jun 27 '15 11:06

imc


2 Answers

This is a whitespace problem. The case clauses need to be indented to the same level.

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

Remember to use only spaces, no tabs.

like image 50
leftaroundabout Avatar answered Oct 20 '22 17:10

leftaroundabout


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

First off, you shouldn't make unsafe things like this: your program will fail. It's much cleaner to keep it as a Maybe Int and operate as such, safely. In other words, this was a simple parse error, but making incomplete functions like this may cause far greater problems in the future.

The problem you've encountered it, how can I do that?

We might make a better function, like this:

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

Which would allow you to write:

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

However, there is a function called fmap, which 'maps' a function over certain data-structures, Maybe included:

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

and if you have imported Control.Applicative, there is a nice operator synonym for it:

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

If you want to know more about these data-structures, called Functors, I would recommend reading Learn-you a Haskell.

like image 42
AJF Avatar answered Oct 20 '22 17:10

AJF