Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Thanks. I sometimes wonder, is there a way in Haskell to display a type signature of a function for a particular instance? For example, is there a way to display type of get when used as an instance of State ? I know I can derive it but I would sometimes like to see if I am correct..


There's a hack you can use until Type Holes lands in production GHCi. If you turn on ImplicitParams you can write

  getAny :: (Random a) => State StdGen a
  getAny = do g      <- ?whatAmI get
              (x,g') <- return $ random g
              put g'
              return x
which will fail the type checker because your type didn't include the information about what ?whatAmI is---the error will be something like "could not find definition of ?whatAmI :: State StdGen StdGen -> State StdGen StdGen", although you may only get partial information as the compiler may complain about your undefined function before it's resolved what you're looking for.

You can also leave off the type annotation and GHCi will infer the type of ?whatAmI. Then if you check the type of "getAny" you'll see

    getAny
      :: (?whatAmI::m s -> n s', RandomGen s', Random b,
          MonadState s m, MonadState s' n) =>
         m b
which provides all of the information the typechecker knows all in one go. Take note that the type it derives is somewhat more general than the one we want since it allows ?whatAmI to transform the involved monad. Obviously "get" doesn't do this.


Some vim and emacs plugins can give you the type of subexpressions like this. Namely, you want the ghc-mod plugin since it provides the hooks into the compiler to query type information.


Is there a way to do this in ghci? I know the :t command, but I don't know how to say that I want a specific instance.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: