【问题标题】:Haskell / GHCi - loading modules from different directoriesHaskell / GHCi - 从不同目录加载模块
【发布时间】:2011-07-07 05:07:31
【问题描述】:

我的 haskell 应用程序的目录结构如下:

src/
    utils/Utils.hs
    subsystem/Subsystem.hs

Subsystem 模块导入 Utils 模块。我想在 GHCi 中手动测试这段代码。

问题是 GHCi 似乎只在寻找'.'(当前目录)中可用的模块,所以我将Utils.hs 复制到子系统文件夹并能够手动测试Subsytem.hs。有一个更好的方法吗?例如,我想在 src 目录中启动 GHCi 并让它在 ./utils 和 ./subsystem 目录中搜索模块。我可以指定 GHCi 的模块路径吗?

【问题讨论】:

    标签: haskell ghci haskell-platform


    【解决方案1】:

    您可以使用-i 选项告诉 GHCi 在哪里搜索模块:

    ghci Foo.Bar -isrc
    

    这会将src/Foo/Bar.hs 加载到 GHCi 中。这样,您还可以像这样指定两个不同的目录:

    ghci Bar.hs -i.:config 
    

    它将在 ./ 和 ./config/ 中查找依赖项。

    See the GHC user's guide for more information about the module search path.

    【讨论】:

      【解决方案2】:

      默认情况下,当 GHC 查找模块时,它将 Foo.Bar 解释为 Foo/Bar.hs。因此,如果您有一个项目,则可以在顶级目录中将模块 Utils 作为 Utils.hs 并将模块 Utils.Fishcakes 作为 Utils/Fishcakes.hs。请注意,Utils.hs 可以与名为Utils 的目录一起存在,或者两者都可以独立存在。一种常见的风格往往是使用顶级模块来简单地从层次结构中它下面的模块重新导出东西,但这不是必需的。 GHC User Guide 涵盖了上述行为,并描述了支持哪些其他选项。

      据我所知,在大多数情况下,代码要么使用上述默认结构,要么使用作为 cabal 构建的一部分指定的其他结构,或者期望作为库安装。

      【讨论】:

      • 感谢您的回复。我能够通过执行以下操作来解决此问题:在 src/ 下创建包含 Utils.hs 和 Subsystem.hs 文件的 Utils 和 Subsystem 目录,其中包含 Utils.Utils 和 Subsystem.Subsystem 模块。然后我可以从 src/ 运行 GHCi,然后执行 :add Subsystem.Subsystem.
      【解决方案3】:

      您可以使用以下内容创建一个 .ghci 文件:

      :set -isrc -iutils -isubsystem

      【讨论】:

        【解决方案4】:

        如果您的项目如下所示...

        src/
            utils/Utils.hs
            subsystem/Subsystem.hs
        .....
        myproject.cabal
        Setup.hs
        

        你可以在项目的根目录下创建一个.ghci文件,src、myproject.cabal和Setup.hs所在的目录。.gchi的内容应该是这个..

        :set -isrc/utils -isrc/subsystem
        

        现在您可以从项目的根目录调用 ghci,它会自动加载任何链接的模块。

        $ ghci
        GHCi, version 7.8.3: http://www.haskell.org/ghc/  :? for help
        Loading package ghc-prim ... linking ... done.
        Loading package integer-gmp ... linking ... done.
        Loading package base ... linking ... done.
        Prelude>:load src/subsystem/Subsystem.hs
        ... should load Subsystem.hs
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多