2

This snippet is from LYAH:

instance (Eq m) => Eq (Maybe m) where     

Just x == Just y = x == y      
Nothing == Nothing = True     
 _ == _ = False

I am totally confused as to what x and y are supposed to be since they are not defined anywhere. Can anyone help me understand this?

2 Answers 2

3

Well, == is an infix function, you can read this as a pattern matching on:

(==) (Just x) (Just y)

In which case it is clear that x and y are the function parameters in the pattern matching.

A simpler example can be shown (without type classes) as:

areBothFive:: Int -> Int -> Bool
5 `areBothFive` 5 = True 
x `areBothFive` y = False -- the x and y are variables in the pattern match here

areBothFive 5 5 -- true
areBothFive 4 5 -- false

Here's a fiddle illustrating the issue.

LYAH gives an example using this syntax in the "Syntax in Functions" chapter.

Sign up to request clarification or add additional context in comments.

Comments

2

They are there to deconstruct the pattern Just _ - so:

  • let (Just x) = Just 5 will give you x <- 5
  • on the other hand let (Just x) = Nothing will just match (and fall through to another case - here it will be the _ == _

remark

the let is just there so that you can try this out in GHCi:

> let (Just x) = Just 5
> x
5

> let (Just x) = Nothing
> x
*** Exception: <interactive>:4:5-22: Irrefutable pattern failed for pattern (Just x)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.