Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

func :: Maybe(Int) -> Maybe(Int)

I've done some research but couldn't find anything. I don't understand how a function like this works:

func :: Maybe (Int) -> Maybe (Int)

How am I supposed to do the pattern matching? I've tried this but it didn't work:

func Just a  = Just a | otherwise = Nothing
func Nothing = Just Nothing | otherwise = Nothing

How can I make this work?

Error message:

exercises6.hs:83:22: error: parse error on input ‘|’
   |
83 | func Just a = Just a | otherwise = Nothing
   |                      ^

1 Answers

You pattern match on the two possible cases. A Maybe a has two data constructors: a Nothing, and a Just … with the value it wraps. There is no | otherwise part when you do pattern matching. The pipe character (|) is used for guards [lyah].

So you can for example increment the value in a Just with:

func :: Maybe Int -> Maybe Int
func (Just x) = Just (x+1)
func Nothing = Nothing

The brackets around Just x are required here, as @chepner says. Otherwise it will be parsed as if Just is the first parameter, and x is a second parameter.

Since Maybe is an instance of the Functor typeclass, you can make use of fmap :: Functor f => (a -> b) -> f a -> f b here:

func :: Maybe Int -> Maybe Int
func = fmap (1+)
like image 152
Willem Van Onsem Avatar answered Feb 22 '26 20:02

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!