Use of Haskell state monad a code smell?

前端 未结 8 2101
悲哀的现实
悲哀的现实 2020-12-22 19:56

God I hate the term \"code smell\", but I can\'t think of anything more accurate.

I\'m designing a high-level language & compiler to Whitespace in my spare time

8条回答
  •  旧时难觅i
    2020-12-22 20:27

    Have you looked at Attribute grammars (AG)? (More info on wikipedia and an article in the Monad Reader)?

    With AG you can add attributes to a syntax tree. These attributes are separated in synthesized and inherited attributes.

    Synthesized attributes are things you generate (or synthesize) from your syntax tree, this could be the generated code, or all comments, or whatever else your interested in.

    Inherited attributes are input to your syntax tree, this could be the environment, or a list of labels to use during code generation.

    At Utrecht University we use the Attribute Grammar System (UUAGC) to write compilers. This is a pre-processor which generates haskell code (.hs files) from the provided .ag files.


    Although, if you're still learning Haskell, then maybe this is not the time to start learning yet another layer of abstraction over that.

    In that case, you could manually write the sort of code that attributes grammars generate for you, for example:

    data AbstractSyntax = Literal Int | Block AbstractSyntax
                        | Comment String AbstractSyntax
    
    compile :: AbstractSyntax -> [Label] -> (Code, Comments)
    compile (Literal x) _      = (generateCode x, [])
    compile (Block ast) (l:ls) = let (code', comments) = compile ast ls
                                 in (labelCode l code', comments)
    compile (Comment s ast) ls = let (code, comments') = compile ast ls
                                 in (code, s : comments')
    
    generateCode :: Int -> Code
    labelCode :: Label -> Code -> Code
    

提交回复
热议问题