我正在用 Haskell 编写一个编译器,所以我们有一个 拍品 (或者至少对我来说似乎很多)data
s 和构造函数,例如:
data DataType
= Int | Float | Bool | Char | Range | Type
| String Width
| Record (Lexeme Identifier) (Seq Field) Width
| Union (Lexeme Identifier) (Seq Field) Width
| Array (Lexeme DataType) (Lexeme Expression) Width
| UserDef (Lexeme Identifier)
| Void | TypeError -- For compiler use
data Statement
-- Language
= StNoop
| StAssign (Lexeme Access) (Lexeme Expression)
-- Definitions
| StDeclaration (Lexeme Declaration)
| StDeclarationList (DeclarationList Expression)
| StStructDefinition (Lexeme DataType)
-- Functions
| StReturn (Lexeme Expression)
| StFunctionDef (Lexeme Declaration) (Seq (Lexeme DataType))
| StFunctionImp (Lexeme Identifier) (Seq (Lexeme Identifier)) StBlock
| StProcedureCall (Lexeme Identifier) (Seq (Lexeme Expression))
-- I/O
| StRead (Seq (Lexeme Access))
| StPrint (Seq (Lexeme Expression))
-- Conditional
| StIf (Lexeme Expression) StBlock StBlock
| StCase (Lexeme Expression) (Seq (Lexeme When)) StBlock
-- Loops
| StLoop StBlock (Lexeme Expression) StBlock
| StFor (Lexeme Identifier) (Lexeme Expression) StBlock
| StBreak
| StContinue
还有很多。您可能已经注意到重复的
Lexeme a
在许多构造函数中。词位如下
data
type Position = (Int, Int)
data Lexeme a = Lex
{ lexInfo :: a
, lexPosn :: Position
}
所以它用于保存
Position
的信息。程序文件中的一个元素,用于报告错误和警告。有没有更简单的方法来处理
Position
的信息的保留?问题?
最佳答案
我习惯于看到另一个可以选择性地用来保存词法信息的构造函数:
data Expression = ... all the old Exprs
| ExprPos Position Expression
data Declaration = ... decls ...
| DeclPos Position Declaration
现在在您的
Statement
和其他数据类型,而不是像这样的东西:| StFor (Lexeme Identifier) (Lexeme Expression) StBlock
你有:
| StFor Identifier Expression StBlock
关于haskell - 在许多不同的数据中重复某个功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25693969/