10

I was wondering, if there is a standard, canonical way in Haskell to write not only a parser for a specific file format, but also a writer.

In my case, I need to parse a data file for analysis. However, I also simulate data to be analyzed and save it in the same file format. I could now write a parser using Parsec or something equivalent and also write functions that perform the text output in the way that it is needed, but whenever I change my file format, I would have to change two functions in my code. Is there a better way to achieve this goal?

Thank you, Dominik

jberryman
  • 16,334
  • 5
  • 42
  • 83
Dominik Schrempf
  • 827
  • 8
  • 14
  • 1
    I think the simplest thing to do would be to define a data type representing the syntax of your file and then write a separate parser and pretty printer as you thought. This is what most language libraries do for example. – daniel gratzer Jul 21 '17 at 14:21
  • 2
    Here are some recent relevant threads on reddit: [1](https://www.reddit.com/r/haskell/comments/6aqvgj/parser_libraries_with_ast_output/), [2](https://www.reddit.com/r/haskell/comments/66o3lp/i_think_this_is_a_really_stupid_question_inverse/) IMO this technology still seems quite experimental. – Li-yao Xia Jul 21 '17 at 14:53
  • What you want to do is define a grammar, and use some library to generate a parser and pretty-printer automatically. There are a number of libraries that claim to be able to do that but recommending one is probably OT (I would if I had experience with any of them) – jberryman Jul 21 '17 at 18:46
  • 8
    I strongly disagree with the close votes. This question isn't asking to locate an off-site resource; it's asking how to solve a problem that's on-topic for stack overflow. It's Ok for answers to questions to be "you can solve this problem with this library"; those answers are factual and not opinion-based; it doesn't lead to the non-constructive interactions the rule is designed to avoid. – Cirdec Jul 21 '17 at 20:02

1 Answers1

5

The BNFC-meta package https://hackage.haskell.org/package/BNFC-meta-0.4.0.3

might be what you looking for

"Specifically, given a quasi-quoted LBNF grammar (as used by the BNF Converter) it generates (using Template Haskell) a LALR parser and pretty pretty printer for the language."

update: found this package that also seems to fulfill the objective (not tested yet) http://hackage.haskell.org/package/syntax

neu-rah
  • 1,662
  • 19
  • 32
  • Thank you very much for the comments and your answer. It is indeed the concept of a /grammar/ that I was looking for. Apart from the BNFC-meta package, the [second link](https://www.reddit.com/r/haskell/comments/66o3lp/i_think_this_is_a_really_stupid_question_inverse/) of Li-yao Xia also mentions the interesting [syntax](https://hackage.haskell.org/package/syntax) library. – Dominik Schrempf Aug 07 '17 at 08:45