I’m having a hard time understanding Higher Kind vs Higher Rank types. Kind is pretty simple (thanks Haskell literature for that) and I used to think rank is like kind when talking about types but apparently not! I read the Wikipedia article to no avail. So can someone please explain what is a Rank? and what is meant by Higher Rank? Higher Rank Polymorphism? how that comes to Kinds (if any) ? Comparing Scala and Haskell would be awesome too.
Share
The concept of rank is not really related to the concept of kinds.
The rank of a polymorphic type system describes where
foralls may appear in types. In a rank-1 type systemforalls may only appear at the outermost level, in a rank-2 type system they may appear at one level of nesting and so on.So for example
forall a. Show a => (a -> String) -> a -> Stringwould be a rank-1 type andforall a. Show a => (forall b. Show b => b -> String) -> a -> Stringwould be a rank-2 type. The difference between those two types is that in the first case, the first argument to the function can be any function that takes one showable argument and returns a String. So a function of typeInt -> Stringwould be a valid first argument (like a hypothetical functionintToString), so would a function of typeforall a. Show a => a -> String(likeshow). In the second case only a function of typeforall a. Show a => a -> Stringwould be a valid argument, i.e.showwould be okay, butintToStringwouldn’t be. As a consequence the following function would be a legal function of the second type, but not the first (where++is supposed to represent string concatenation):Note that here the function
fis applied to (potentially) three different types of arguments. So iffwere the functionintToStringthis would not work.Both Haskell and Scala are Rank-1 (so the above function can not be written in those languages) by default. But GHC contains a language extension to enable Rank-2 polymorphism and another one to enable Rank-n polymorphism for arbitrary n.