user1286894
user1286894

Reputation: 43

type signature between function and class

data Maybe' a = Nothing' | Just' a deriving (Show)

class From' t 
    where from' :: t a -> a

instance From' Maybe' 
    where from' (Just' x) = x

This works.

But...

from2 :: t a -> a 
from2 (Just' x)  = x

Couldn't match type `t' with `Maybe''
  `t' is a rigid type variable bound by
      the type signature for from2 :: t a -> a at test.hs:11:1
In the pattern: Just' x
In an equation for `from2': from2 (Just' x) = x

I don't know why it doesn't work.

Upvotes: 1

Views: 83

Answers (1)

ehird
ehird

Reputation: 40797

In the instance, t is defined to be Maybe', so from' has to have type Maybe' a -> a. If you write:

from2 :: Maybe' a -> a

then it'll work. The error message is saying that your type signature claims that from2 could turn t a into a for any choice of t, but your definition only works if t is Maybe'.

By the way, this function is already defined for the standard Maybe type as fromJust in the Data.Maybe module, but you probably shouldn't use it, since it'll give an unhelpful error message if you ever pass it Nothing. Of course, if it's just an example, then that's fine.

Upvotes: 4

Related Questions