typeclasses / haskell-phrasebook

The Haskell Phrasebook: a quick intro to Haskell via small annotated example programs
https://typeclasses.com/phrasebook
210 stars 22 forks source link

Asking for the type of an expression #3

Open chris-martin opened 5 years ago

chris-martin commented 5 years ago

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.

ammatsui commented 5 years ago

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