Search code examples
haskelltypespolymorphismhigher-rank-types

What is the purpose of Rank2Types?


I am not really proficient in Haskell, so this might be a very easy question.

What language limitation do Rank2Types solve? Don't functions in Haskell already support polymorphic arguments?


Solution

  • Do not functions in Haskell already support polymorphic arguments?

    They do, but only of rank 1. This means that while you can write a function that takes different types of arguments without this extension, you can't write a function that uses its argument as different types in the same invocation.

    For example the following function can't be typed without this extension because g is used with different argument types in the definition of f:

    f g = g 1 + g "lala"
    

    Note that it's perfectly possible to pass a polymorphic function as an argument to another function. So something like map id ["a","b","c"] is perfectly legal. But the function may only use it as monomorphic. In the example map uses id as if it had type String -> String. And of course you can also pass a simple monomorphic function of the given type instead of id. Without rank2types there is no way for a function to require that its argument must be a polymorphic function and thus also no way to use it as a polymorphic function.