【问题标题】:Exporting multiple modules in one file在一个文件中导出多个模块
【发布时间】:2019-09-22 12:47:35
【问题描述】:

我需要在一个 Haskell 文件中导出两个模块。现在,我有

module name (important,functions) where
module nameForTesting where

-- the code is here

但是,它给了我这个错误:

filename.hs:5:1: error: parse error on input ‘module’

我该如何解决这个问题?

【问题讨论】:

  • 一个文件属于一个模块。但是,您可以重新导入一个模块,然后导出一个子集。
  • 我不确定我是否理解。你能解释一下你的意思吗?

标签: haskell import module


【解决方案1】:

据我所知,同一个文件中不能有多个模块。 This answer 似乎证实了这一点。

你可以做的是创建第二个模块,重新导出一些功能。所以我们首先创建一个文件NameForTesting.hs

-- NameForTesting.hs
module NameForTesting where

important :: Int
important = 42

functions :: Int -> Int
functions = (42 +)

foo :: Int
foo = 21

然后我们可以构造第二个文件Name.hs,它导入NameForTesting模块,但只导出importantfunctions

-- Name.hs
module Name(important, functions) where

import NameForTesting

Name 模块将在这里仅导出从 NameForTesting 模块导入的 importantfunctions

【讨论】:

    【解决方案2】:

    您需要区分定义一个模块和导出该模块的名称;它们是两个独立的步骤。

    一个文件只能定义一个模块。但是,您可以导出从其他模块导入的名称作为该模块的一部分。例如,

    module MyModule (foo, bar) where
    
    import OtherModule (bar) -- Let's say bar :: Int -> String
    
    foo :: Int -> Int
    foo x = x + 3
    

    MyModule 没有定义bar;相反,它从OtherModule 导入它,然后将其作为自身的一部分导出。然后MyModule 的用户无需显式导入OtherModule 即可访问bar

    import MyModule
    
    main = putStrLn (bar (foo 9))
    

    【讨论】:

      猜你喜欢
      • 2019-02-13
      • 1970-01-01
      • 2018-02-14
      • 2021-04-12
      • 2018-02-12
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多