Suppose I have a mathematical expression in the form of a tree in OCaml. It is represented as an algebraic type like this:
type expr = Number of int |Plus of expr*expr
Well, this is a very simplified definition, but enough to describe the problem.
I want to convert it to a string in reverse polarity format so that Plus (Number i, Number j) becomes (+ ij) . Direct implementation will be
let rec convert = function Number i -> string_of_int i |Plus (a,b) -> (let s = convert a in let p = convert b in "(+"^s^" "^p^")")
But the fact is that it is incredibly slow at some entrance (which has a large depth of tree). For example, this input works on my machine for 5 seconds:
let rec make_pain so_far = function 0 -> so_far |i -> make_pain (Plus (Number 1,so_far)) (i-1) let pain = make_pain (Number 1) 20000 let converted = convert pain
It seems that string concatenation x^y , where y is the long string, is a performance issue. Indeed, if you replace the expression "(+"^s^" "^p^")" with a simple s^p , it will become much faster.
Using printf instead of concatenation does not make it faster. Converting to C may help, but is there no OCaml solution?
performance string ocaml
Pavel shved
source share