Haskell- (type declaration), what is an "a"?

This is perhaps a very simple question, but, nevertheless, it does not seem to have been addressed in SO.

I recently took Haskell and so far, type declarations have consisted mainly of the following:

Int Bool Float etc, etc 

Now I get into lists, and I see type declarations that use a , for example, in the following function that iterates through an associative list:

 contains :: Int -> [(Int,a)] -> [a] contains x list = [values | (key,values)<-list, x==key] 

Can someone explain to you what this a is and how it works? From the observation, it seems to represent each type. Does this mean that I can enter any list of any type as a parameter?

+5
source share
2 answers

Yes, you are right, it represents "any type" - the limitation is that all a in a given type signature must be allowed to the same type. Thus, you can enter a list of any type, but when using contains to find the value in the list, the value you are looking for must be of the same type as the list items, which, of course, makes sense.

+12
source

In Haskell, uppercase types are concrete types ( Int , Bool ) or type constructors ( Maybe , Either ), and lowercase types are type variables. The function is implicitly common to all type variables that it uses, so this is:

 contains :: Int -> [(Int, a)] -> [a] 

Is a shorthand for this *:

 contains :: forall a. Int -> [(Int, a)] -> [a] 

In C ++ forall is written template :

 template<typename a> list<a> contains(int, list<pair<int, a>>); 

In Java and C #, it is written using angle brackets:

 list<a> contains<a>(int, list<pair<int, a>>); 

Of course, in these languages ​​general type variables are often called T , U , V , and in Haskell theyre often called a , b , c . This is just a difference of convention.

* This syntax is activated by the -XExplicitForAll flag in the GHC, as well as other extensions.

+1
source

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


All Articles