在许多不同的数据中重复某个功能 [英] Repeat a certain functionality in a lot of different datas

查看:97
本文介绍了在许多不同的数据中重复某个功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Haskell编写了一个编译器,所以我们有一个很多 (或者至少对我来说看起来很像) data s和构造函数,如下所示:

I'm writing a compiler in Haskell, so we have a lot (or at least it seems like a lot for me) of datas and constructors, such as the followings:

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

And many more. You may have noticed the repeating Lexeme a in many of the constructors.

Lexeme是以下 data

Lexeme is the following data

type Position = (Int, Int)

data Lexeme a = Lex
    { lexInfo :: a
    , lexPosn :: Position
    }

因此,它可以将元素的位置的信息保存在程序的文件中,用于报告错误和警告。

So it works for keeping the information of the Position of an element in the program's file, for reporting errors and warnings.

推荐答案

可以将 Lexeme 应用程序:

One could move "up" the Lexeme application:

type Access = Lexeme Access'
data Access' = ...
type Expression = Lexeme Expression'
data Expression' = ...
-- etc.
data Statement
    -- Language
    = StNoop
    | StAssign Access Expression
    -- Definitions
    | StDeclaration      Declaration
    | StDeclarationList  (DeclarationList Expression')  -- maybe you can also use Expression here?
    | StStructDefinition DataType
    ...

通过这种方式,您可以应用 Lexeme 每种类型定义一次,而不是每种类型使用

In this way you apply Lexeme once every type definition, instead of once every type use.

这篇关于在许多不同的数据中重复某个功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆