3

So basically I wrote an tiny parser, and in the parser, I defined a large amount of types as follows

let stackop = PUSH | POP
and systemop = INT | IN | OUT
and arithmop = ADC | ADD | XADD | SUB
           | MUL | IMUL | DIV | IDIV
           | INC | DEC | NEG
and logicop = AND | OR | XOR
and rolop = ROL | SHL | SHR | SHLD |SHRD | SAL | SAR
.....

So currently after parse, I want to implement a typical "pretty_print" function to print out the syntax tree

Basically, as far as I know, I have to implement a pp_print function, that transform all these types into its corresponding string like this:

let pp_print = function
  | PUSH -> "push" | POP -> "pop"
  ....

But my question is that there are too many types to be printed, and it seems tedious to write them all manually in the above way.

So I am wondering if there is an easier approach, for example, like

let t_str = s.type in 
  print_string t_str       
(*I know it is not typical OCaml style, I just want to demonstrate*) 

Is it possible..? Could anyone give me some help?

lllllllllllll
  • 8,519
  • 9
  • 45
  • 80
  • If you are willing to use CamlP4 then the tutorial docs have an example of this exact thing in sectciton 7.5. http://caml.inria.fr/pub/docs/tutorial-camlp4/tutorial007.html Otherwise I am not sure if it is possible from within Ocaml. Maybe just generate the code from the type definition? – stonemetal Apr 23 '14 at 16:46
  • http://stackoverflow.com/questions/1777720/hashtable-indexed-on-several-fields – ygrek Apr 23 '14 at 17:30

1 Answers1

3

You could use the deriving syntax extension

So for example, you would annotate your type like this:

 type stackop = PUSH | POP deriving (Show, Enum)

Then later on you can use:

Show.show<stackop> some_stackop 

to pretty print a value of a stackop type.

aneccodeal
  • 8,531
  • 7
  • 45
  • 74