Haskell对模块的引用

时间:2012-07-21 09:02:43

标签: haskell module

是否可以参考haskell中的模块?我有几个模块,每个模块都暴露相同的接口(两个相同名称和签名的功能)。是否可以有一个这样的模块列表,以调用每个模块的功能。

2 个答案:

答案 0 :(得分:3)

如何定义接口的数据类型?每个模块提供数据类型的单个实例,然后您可以遍历所有实例。

-- ModuleInterface.hs
-- Replace types of the functions with actual types
data ModuleInterface = ModuleInterface (Int -> Bool -> Int) (String -> Int)

-- ModuleA.hs
moduleInterface :: ModuleInterface
moduleInterface = ModuleInterface f1 f2
-- Declare f1 and f2

-- ModuleB.hs
moduleInterface :: ModuleInterface
moduleInterface = ModuleInterface f1 f2
-- Declare f1 and f2

-- Main.hs
-- Simple example showing how to "call" all of the functions. If you are doing
-- IO, then you would have to use something like mapM.
transform :: [ModuleInterface] -> Int -> Bool -> String -> [(Int, Int)]
transform interfaces i b s = map f interfaces
    where f (ModuleInterface g h) = (g i b, h s)

答案 1 :(得分:0)

我不确定你想要什么,但通常只需使用合格的导入即可解决名称冲突。在下面的示例中,我会观察S.M.以明确说明函数或类型所在的模块。

import qualified Data.Set as S
import qualified Data.Map as M

mySet :: S.Set Int 
mySet = S.fromList [1,2,3]

myMap :: M.Map String Int 
myMap = M.fromList [("a", 1), ("b", 2), ("c", 3)] 

main = do
  print mySet
  print myMap
  print $ S.member 2 mySet
  print $ M.lookup "c" myMap

但是从您的问题看来,您正在寻找一些元编程解决方案,其中您有是模块,比如说setModule, mapModule :: Module,并在getFunctions :: Module -> [Functions]上使用getter }。我确定这不存在,因为它不适合静态类型的语言。但是,如果你严重滥用模板Haskell或宏,你可能会蠢蠢欲动。