Implicit type parameters in a Haskell class definition?

It usually seems that the following is illegal:

class Foo a where foo :: a -> b -> a 

It makes sense; How do we know that b ?

However, if we look at the definition of Functor:

 class Functor f where fmap :: (a -> b) -> fa -> fb 

we see a and b , although we specify f as a type variable. I assume this is allowed because the compiler sees, for example. fa and can understand that f itself must take a , so it's safe to use that a elsewhere in our definition of Functor. Am I right?

+4
source share
2 answers

Look at each line separately.

 class Functor f where 

This declares a single parameter class called Functor ; satisfying this type will be called f .

  fmap :: (a -> b) -> fa -> fb 

Like any function definition, all variables of a free type are implicitly forall ed - they can be replaced with anything. However, thanks to the first line, f is in scope. So fmap has a signature like fmap :: forall a b. Functor f => (a -> b) -> fa -> fb fmap :: forall a b. Functor f => (a -> b) -> fa -> fb . In other words, each functor must have a fmap definition that can work for any a and b , and f must have the form (type type) * -> * ; that is, it must be a type that accepts another type, for example [] or Maybe or IO .

What you said is wrong; a not special, and if we had another function in Functor , she would not see the same a or b . However, the compiler uses the fa bit to figure out what type f should be. In addition, your Foo class is completely legal; I could specify an instance as follows

 instance Foo (a -> b) where foo f _ = f 

This satisfies foo :: a -> b -> a for any b ; note that b in Foo (a -> b) is different. Admittedly, this is not a very interesting example, but it is completely legal.

+6
source

No need to "know." It just requires type checking (i.e. not subject to type checking). b may be any; and the function foo should be able to accept any type as the second parameter.

Consider the const function from Prelude:

 const :: a -> b -> a const x _ = x 

How does he “know” that b (or a , for that matter)?

+3
source

Source: https://habr.com/ru/post/1315623/


All Articles