2

Can someone explain to me why the following doesn't work?

foo :: Int -> ST s Int
foo = return

bar :: (forall s. ST s Int) -> Int
bar = runST

baz :: Int -> Int
baz = bar . foo

Error thrown for `baz:

Couldn't match type `ST s0 Int' with `forall s. ST s Int'
Expected type: Int -> forall s. ST s Int
  Actual type: Int -> ST s0 Int

I assumed that since bar can accept any s in its argument, the result of foo (which is a particular s) should be okay.

EDIT: Forgot to add. This works as expected:

quux :: Int -> Int
quux x = bar $ foo x
  • [This answer](http://stackoverflow.com/a/9469942/839246) might help – bheklilr Aug 12 '14 at 02:01
  • Basically, the answer seems to be that there is a special rule in the type checker just for `$` because people like to write `runST $ do ...`, but the type checker really can't in general handle these higher ranked types because SPJ (who has worked on at least 2 papers on the subject) thinks it's rather too complicated to leave in GHC, and instead opted for a simpler, albeit ad-hoc, solution of special rules for `$`. Long story short, you've gotta use `$` instead of `.` to keep the type checker from being confused. – bheklilr Aug 12 '14 at 02:04
  • @bheklilr, thanks! It's strange that SO didn't suggest that question to me when I was typing this one in. But it showed up in the "Related" section on the sidebar as soon as it was posted. – ars-longa-vita-brevis Aug 12 '14 at 02:06
  • If you're curious, [there's been a recent meta discussion about the difference between different search methods](http://meta.stackoverflow.com/questions/268318/why-is-the-this-question-might-exist-search-better-than-the-normal-search) – bheklilr Aug 12 '14 at 02:08
  • @bheklilr, do you know what the difference is between `(a -> forall s1. ST s1 a)` and `(a -> ST s a)`. Because, as explained in the answer, if you explicitly define the type of the second argument of `(.)` to `(a -> forall s1. ST s1 a)`, it type checks. – ars-longa-vita-brevis Aug 12 '14 at 02:09
  • Not in so many words, no... I haven't used higher ranked types terribly much myself, but found that answer via a google search because I was curious myself. – bheklilr Aug 12 '14 at 02:11
  • Also, if it's OK with you, would you mind if I closed this question as a duplicate of the one I linked above? – bheklilr Aug 12 '14 at 02:11
  • Yes, please do. Is it okay if I open a new question with the question I asked in my last comment? I'm still curious about why that method works. – ars-longa-vita-brevis Aug 12 '14 at 02:12
  • Go for it, I'll mark this as duplicate but I'll be interested to see what answers you get on your question. – bheklilr Aug 12 '14 at 02:15

0 Answers0