Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will GHC strip out unused imports?

Tags:

haskell

ghc

When I don’t use certain imports from the main function (which should be easily detectable), will GHC strip out the corresponding bindings?

Example:

import Text.Parsec (parse)
import My.Testframework (test)

main = parse …

tests = test …

Will My.Testframework be linked in the executable?

like image 260
Profpatsch Avatar asked May 16 '15 22:05

Profpatsch


1 Answers

I did this simple test:

import Data.Map as M
import Data.Text as T

main = do
  let m = M.fromList [(1, 2), (3, 4)]
  putStrLn $ show m

and got:

$ ghc imports.hs
$ $ ls -l imports
-rwxr-xr-x+ 1 erik  staff  1583112 May 17 10:56 imports

I then commented out the unused Data.Text import:

import Data.Map as M
-- import Data.Text as T

main = do
  let m = M.fromList [(1, 2), (3, 4)]
  putStrLn $ show m

and got this:

$ ghc imports.hs 
$ ls -l imports
-rwxr-xr-x+ 1 erik  staff  1583112 May 17 10:56 imports

Nothing changed, so I must assume Data.Text was already ignored since it was unused.


I then tried 2 more variants.

Leaving in the Data.Map import and the fromList call, but not using the value in m:

import Data.Map as M
-- import Data.Text as T

main = do
  let m = M.fromList [(1, 2), (3, 4)]
  putStrLn "hello"

which got me:

$ ghc imports.hs 
$ ls -l imports
-rwxr-xr-x+ 1 erik  staff  1505292 May 17 10:56 imports

I then also removed the construction of m using fromList:

import Data.Map as M
-- import Data.Text as T

main = do
  putStrLn "hello"

which got me:

$ ghc imports.hs 
$ ls -l imports
-rwxr-xr-x+ 1 erik  staff  1505284 May 17 10:56 imports

— the size barely changed.

So my interpretation is that even if you're importing a library and using it superficially, but the use itself is unused, GHC will not link libraries whose imports are unused.

like image 133
Erik Kaplun Avatar answered Sep 21 '22 18:09

Erik Kaplun