difference between isNothing and (== Nothing) in Haskell?

  • A+

I'm confused about why the two functions below involving Nothing are different:

coalesce  m1 m2 = if  isNothing m1 then m2 else m1  coalesce' m1 m2 = if  (m1 == Nothing) then m2 else m1 

The first one has type:

λ> :t coalesce coalesce :: Maybe a -> Maybe a -> Maybe a 

as expected. But the second one has:

λ> :t coalesce' coalesce' :: Eq a => Maybe a -> Maybe a -> Maybe a 

Why does using (==Nothing) introduce the Eq a constraint?

(GHC 8.2.2)

== is a function Eq a => a -> a -> Bool. You’re making one of its operands Nothing, so a is a Maybe b for some type b, but that Eq a restriction still applies – the Maybe b has to have an Eq instance. Maybe b includes a definition for such an instance – Eq (Maybe b) – for all Eq b.

In other words, == is just a function and it doesn’t know ahead of time that you’re providing Nothing as an argument. It only knows it’s some Maybe a, and it needs to be able to compare equality if it happens to be a Just ….

In other other words, here’s how you can define the == that already exists for Maybes:

equals a b = case a of     Nothing -> isNothing b     Just x -> case b of         Nothing -> False         Just y -> x == y 

Notice how x == y appears, meaning there must be an Eq instance for the type of x and y.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: