如何将文件拆分为Haskell中的模块?

时间:2009-11-09 04:06:20

标签: haskell

我遇到了模块语法的问题。基本上我正在尝试将我的代码分成两个单独的文件,一个用于我正在创建的对象(AST),一个用于我的所有函数。


    --main.hs
    data AST = Add (AST) (AST)|
               Sub  (AST) (AST)|
               Mult (AST) (AST)|
               Ident Char|
               Num Int
               deriving Show

    aSTLeft (Num    l   ) = (Num l)
    aSTLeft (Ident  l   ) = (Ident l)
    aSTLeft (Add  l _   ) = l
    aSTLeft (Sub  l _   ) = l
    aSTLeft (Mult l _   ) = l
    aSTRight    (Num    r   ) = (Num r)
    aSTRight    (Ident  r   ) = (Ident r)
    aSTRight    (Add  _ r   ) = r
    aSTRight    (Sub  _ r   ) = r
    aSTRight    (Mult _ r   ) = r

    isNum (Num x) = True
    isNum (Ident x) = False
    isNum (Add  (x)(y)) = False
    isNum (Sub  (x)(y)) = False
    isNum (Mult (x)(y)) = False

    --a lot more functions here

这很好用,但是当我尝试将AST数据类型拆分成单独的文件时,


    --ASTADT.hs
    module ASTADT (AST,aSTLeft,aSTRight) where
    data AST =    Add (AST) (AST)|
                  Sub  (AST) (AST)|
                  Mult (AST) (AST)|
                  Ident Char|
                  Num Int
                  deriving Show

    aSTLeft     (Num    l   ) = (Num l)
    aSTLeft     (Ident  l   ) = (Ident l)
    aSTLeft     (Add  l _   ) = l
    aSTLeft     (Sub  l _   ) = l
    aSTLeft     (Mult l _   ) = l
    aSTRight        (Num    r   ) = (Num r)
    aSTRight        (Ident  r   ) = (Ident r)
    aSTRight        (Add  _ r   ) = r
    aSTRight        (Sub  _ r   ) = r
    aSTRight        (Mult _ r   ) = r


    --main.hs
    import ASTADT
    isNum (Num x) = True
    isNum (Ident x) = False
    isNum (Add  (x)(y)) = False
    isNum (Sub  (x)(y)) = False
    isNum (Mult (x)(y)) = False
    --a lot more functions here

加载main.hs我收到错误消息


    Undefined data constructor "Num"

我很确定这只是我的模块语法问题,但我已经完全陷入了几个小时了。我和Hugs一起工作。感谢

2 个答案:

答案 0 :(得分:17)

模块ASTADT仅导出AST数据类型,但不导出其构造函数。如果要从模块用户隐藏数据类型的实现细节,这非常有用。

在您的情况下,您不希望这样,因此要导出构造函数,您可以在数据类型之后的module ... where行中指定它们,例如AST (Num, Ident)。要导出数据类型的所有构造函数,您可以使用(..)而不是明确地命名它们:

module ASTADT (AST (..), aSTLeft, aSTRight) where
...

答案 1 :(得分:4)

数据构造函数的导出声明应该类似于

module ASTADT (AST (Add, Sub, Mult, Ident, Num), aSTLeft, aSTRight) where