· haskell

Haskell: Explicit type declarations in GHCI

On a few occasions I’ve wanted to be able to explicitly define the type of something when trying things out in the Haskell REPL (GHCI) but I didn’t actually realise this was possible until a couple of days ago.

For example say we want to use the read function to parse an input string into an integer.

We could do this:

> read "1" :: Int

But if we just evaluate the function alone and try and assign the result without casting to a type we get an exception:

> let x  = read "1"

    Ambiguous type variable `a0' in the constraint:
      (Read a0) arising from a use of `read'
    Probable fix: add a type signature that fixes these type variable(s)
    In the expression: read "1"
    In an equation for `x': x = read "1"

sepp2k shows how we can provide a type declaration in GHCI in his Stack Over Flow answer:

> let x::Int; x = read "1"
> x

We can also use it when creating a list of integers to ensure they are of type ‘Int’ rather than ‘Integer’ for example:

> let y = [1,2,3]
> :t y
y :: [Integer]

> let y::[Int]; y = [1,2,3]
> :t y
y :: [Int]

It’s a pretty simple thing but I didn’t know it was even possible!

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket