haskell-phrasebook icon indicating copy to clipboard operation
haskell-phrasebook copied to clipboard

Asking for the type of an expression

Open chris-martin opened this issue 6 years ago • 1 comments

We've already covered this once in using the REPL, but here's another quick way of asking for a type that's useful when you're using the text editor + ghcid setup.

If you don't know the type of some expression, leave an underscore (this is called a "hole") and the display in ghcid will tell you what type goes there.

loadConfig :: _
loadConfig = Data.Ini.readIniFile "config.ini"
    • Found type wildcard ‘_’
        standing for ‘IO (Either String Data.Ini.Ini)’

It's pretty magical that you can just type :: _ after an expression to make the type pop up in ghcid.

chris-martin avatar Sep 30 '19 20:09 chris-martin

Or in the middle of a function, when you don't know what to do. For example, when defining a Functor instance for Tree:

data Tree a = Leaf a | Node (Tree a) (Tree a)

instance Functor Tree where
  fmap f (Leaf a)   = Leaf (f a)
  fmap f (Node l r) = Node (_ f l) (_ f r)

Compiler would say:

• Found hole: _ :: (a -> b) -> Tree a -> Tree b
Valid substitutions include
    fmap :: forall (f :: * -> *).
            Functor f =>
            forall a b. (a -> b) -> f a -> f b

So one can use the compiler to get hints about some code

ammatsui avatar Oct 01 '19 19:10 ammatsui