Domanda

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?

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top