haskell - 在许多不同的数据中重复某个功能

标签 haskell

我正在用 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/

相关文章:

haskell - 如何在 Haskell 中打印任何内容

haskell - 当根据某个值调用函数时,Haskell 是否会重新评估该值?

haskell - Haskell递归问题,微小的解析器。否定Expr和let表达式

haskell - 如何通过集合运算组合形状?

haskell - 带(++)的foldl比foldr慢很多

haskell - 无法加载模块 'System.Random'

.net - F# Seq 的一个实现问题

haskell - 此列表如何理解其自身的单位?

haskell - 如何定义一个接受数据类型的自然数并返回它们的总和的函数?

haskell - Writer Monad 现在适合大型惰性列表吗?