Reputation: 91
I am very new to Ocaml and ML in general and I have been having a very fundamental issue. I am using a pattern match and within one match I would like to print two or more concatenated statements. Eg.
chan^"("^var^")"^op2^(poc p); chan^"("^var^")"^op^(poc p)
let processoperatorchange2 t2s2 proc2 op op2=
let rec poc2 p = match p with
| Zero -> "0"
| Pproc (x) -> String.lowercase x
| In(chan, var, _, p, _) -> chan^"("^var^")"^op^(poc2 p); chan^"("^var^")"^op2^(poc2 p)
in poc2 proc2
But then each time I run this, the only statement printed is the last one after the semi colon. Can I get some help with this?
Upvotes: 0
Views: 409
Reputation: 35210
Your function does not print a statement but builds a string, thus it returns a value, and doesn't perform any side-effects. The semicolon operator, when interspersed between two expressions, doesn't combine the value produced from these expressions, thus if you have "hello"; "world"
the result is "world"
. That is what happens in your case when you do
chan^"("^var^")"^op^(poc2 p); chan^"("^var^")"^op2^(poc2 p)
Everything on the lift is just thrown away.
A quick fix would be to concatenate them, e.g.,
chan^"("^var^")"^op^(poc2 p) ^ ";\n" ^ chan^"("^var^")"^op2^(poc2 p)
But in general, an idiomatic way to print AST is to use the Format
module, and implement a recursive pp
function, that has type Format.formatter -> 'a -> unit
. Note the return type, the function doesn't build a string (that is usually an operation of quadratic complexity), but rather prints it into generic output stream.
Upvotes: 2