Haskell RankNTypes - restriction of function domain

149 Views Asked by At

I don't understand why it is so, referring to : What is the purpose of Rank2Types? -> @dfeuer explanation:

... Requiring an argument to be polymorphic doesn't just allow it to be used with multiple types; it also restricts what that function can do with its argument(s) and how it can produce its result ...

f :: (forall a . [a] -> a) -> IO ()

... In fact, no function returning an element not in the list it is given will typecheck

In any explanation of rank-N types I haven't see this effect (or benefit) described, much of the time it was the story about letting the callee choose the type etc... that is clear for me and easy to grasp but I don't see by which virtue (only of extending the rank) we can control/restrict the function domain (and co-domain)...

if somebody could give a deeper insigth of the rankN mechanism involved here. thx

1

There are 1 best solutions below

7
On

Just think about it in terms of polymorphic functions you declare on the top-level. A function with the signature like

foo :: [Int] -> Int

has lots of possible implementations like

foo = sum

foo = length

foo _ = 39

but none of these are legal if the signature were

foo :: [a] -> a

because then you can't give an integer as the result – you must provide a result of whatever type the caller demands. So the implementation is much more restricted: the result must come from the input list, because that's the only place you know the elements have type a no matter what the caller actually instantiates this to. Only something like

foo = head

will work then.

Your RankN signature requires its argument to be such a polymorphic function, i.e. the argument can't be a [Int] -> Int but only the more restrictive [a] -> a.