gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:01:29 25 4
gpt4 key购买 nike

我对模块的语法有疑问。基本上我试图将我的代码分成两个单独的文件,一个用于我正在创建的对象 (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 合作。谢谢

最佳答案

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

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

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

关于haskell - 如何将文件拆分为 Haskell 中的模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1699042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com