I am trying to solve the problem below, but have difficulties figuring out how to print it in the desired format, with parenthesis and numbers / operators.
I have the code below to create expressions, but printing %A using match pattern does not work. I can access values but cannot print them in the desired format. Anyone has suggestions?
let one = Const(1)
let two = Const(2)
let three = Const(3)
let Bin1 = BinOpr(one, "+", two)
let Bin2 = BinOpr(Bin1, "*", three)
The solution to this problem is to implement toString
by pattern matching on expr
and output the appropriate string for Const
and BinOpr
:
Const
, you just need to convert your int
to a string. BinOpr
, you have to build a string of the form (<expr> <op> <expr>)
. Try to implement the function yourself, it's not that difficult but in the case you get stuck, I provide the solution below.
let rec toString expr =
match expr with
| Const x -> string x
| BinOpr (e1, op, e2) -> sprintf "(%s %s %s)" (toString e1) op (toString e2)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.