Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is import of an abstract type not necessary, when using functions which work with values of that type

Tags:

haskell

Following the excercises in chapter 5 of Real World Haskell, I end up with Prettify.hs, which exports among other things an abstract type Doc and a rendering function compact, which is a function from Doc to String. Another file, PrettyJSON.hs exports renderJValue, which ends up giving me a Doc value. In my main, I import just renderJValue and compact, and use the output of the one as input to the other. I am confused why this works. I would think that it would also have been necessary to import the abstract Doc type. Can Haskell see that the two functions fit together without the Doc imported?

For illustration, this is my Main.hs:

module Main where

import System.IO
import SimpleJSON (JValue(..))
import PrettyJSON (renderJValue)
import Prettify (compact)

main = do
    let val = renderJValue $ JString "foo"
    putStrLn $ compact val
    getLine

which outputs

"foo"
like image 531
Boris Avatar asked Feb 23 '11 20:02

Boris


1 Answers

Can Haskell see that the two functions fit together without the Doc imported?

Yes.

To elaborate a bit, what you import is only saying what's in your local namespace, so to mention the Doc type in a type signature, you'd have to import it. ghc is doing a lot of matching up types (and hunting down modules) in the background when loading the dependencies of your code, too, but such matters are implementation detail.

like image 196
barsoap Avatar answered Oct 01 '22 07:10

barsoap