JonasAnon
JonasAnon

Reputation: 195

Importing a haskell module from the parent directory

Given the following directory structure:

root
├── scripts
│   └── script1.hs
└── source
    ├── librarymodule.hs
    └── libraryconfig.txt

Where "librarymodule.hs" would be a library exporting multiple functions, where the output is influenced by the contents of the libraryconfig.txt file in his directory.

script1.hs is the file needing to use the functions declared in librarymodule.hs.

I can't find a solution on the internet for a structure as given above and hoped someone could help out.

Upvotes: 1

Views: 2573

Answers (1)

Li-yao Xia
Li-yao Xia

Reputation: 33519

GHC has a -i option. Under root/scripts/, this will add root/source/ to the search path:

ghc -i../source script1.hs

Also consider packaging your library using cabal so you can install it and use it anywhere without worrying about paths.


Here is a minimal example of a library with data-files:

source/
├── mylibrary.cabal
├── LibraryModule.hs
└── libraryconfig.txt

mylibrary.cabal

name: mylibrary
version: 0.0.1
build-type: Simple
cabal-version: >= 1.10
data-files: libraryconfig.txt

library
  exposed-modules: LibraryModule
  other-modules: Paths_mylibrary
  build-depends: base
  default-language: Haskell2010

LibraryModule.hs

module LibraryModule where

import Paths_mylibrary  -- This module will be generated by cabal

-- Some function that uses the data-file
printConfig :: IO ()
printConfig = do
  n <- getDataFileName "libraryconfig.txt"
  -- Paths_mylibrary.getDataFileName resolves paths for files associated with mylibrary
  c <- readFile n
  print c

See this link for information about the Paths_* module: https://www.haskell.org/cabal/users-guide/developing-packages.html#accessing-data-files-from-package-code

Now running cabal install should install mylibrary.

Then, under scripts/script1.hs, you can just run ghc script1.hs, using the library you installed.

Upvotes: 5

Related Questions