如何从父目录导入Haskell模块?附具体目录结构场景
Hey there! Let's tackle this Haskell module import issue with your directory structure. First, let's recap your setup to make sure I'm on the same page:
root ├── scripts │ └── script1.hs └── source ├── librarymodule.hs └── libraryconfig.txt
You need script1.hs to use functions from librarymodule.hs, which also relies on libraryconfig.txt in the same source directory. Here are a few solid solutions depending on whether you want a quick fix or a more maintainable setup:
Quick Fix: Use GHC's -i Flag
This is the simplest way to get things running without restructuring your project:
- First, fix a common Haskell gotcha: module names must match filenames (case-sensitive). Rename
librarymodule.hstoLibraryModule.hsso you can properly import it asimport LibraryModuleinscript1.hs. - To handle the config file path reliably: Don't use a relative path like
"./libraryconfig.txt"inLibraryModule.hs(since your working directory might berootorscriptswhen running the script). Instead, use a path relative to your project root:import System.FilePath ((</>)) import System.Directory (getCurrentDirectory) getConfigPath :: IO FilePath getConfigPath = do projectRoot <- getCurrentDirectory return $ projectRoot </> "source" </> "libraryconfig.txt" - Compile or run
script1.hsfrom therootdirectory with the-iflag to tell GHC where to find thesourcemodule:# Compile to an executable ghc -isource scripts/script1.hs # Or run directly without compiling runhaskell -isource scripts/script1.hs
Maintainable Setup: Cabal Project
If you plan to expand this project, using Cabal (Haskell's official build tool) will make dependency and resource management easier:
- Create a
myproject.cabalfile in yourrootdirectory with this content:cabal-version: 3.0 name: myproject version: 0.1.0.0 executable script1 main-is: script1.hs hs-source-dirs: scripts, source build-depends: base >=4.14 && <5 default-language: Haskell2010 data-files: source/libraryconfig.txt - Update
LibraryModule.hsto use Cabal's auto-generated path module to find the config file (this works even if you install the project later):import Paths_myproject (getDataFileName) getConfigPath :: IO FilePath getConfigPath = getDataFileName "source/libraryconfig.txt" - Run your script with:
cabal run script1
Alternative: Stack Project
If you prefer using Stack (a popular Haskell toolchain manager), follow these steps:
- Run
stack initin yourrootdirectory to generate apackage.yamlandstack.yaml. - Edit
package.yamlto include your source directories and config file:name: myproject version: 0.1.0.0 executables: script1: main: script1.hs source-dirs: scripts, source ghc-options: - -threaded - -rtsopts - -with-rtsopts=-N dependencies: - base >=4.14 && <5 data-files: source/libraryconfig.txt - Use the same
Paths_myprojectapproach inLibraryModule.hsas the Cabal solution to fetch the config path. - Run your script with:
stack run script1
内容的提问来源于stack exchange,提问作者JonasAnon

