How do you append a char to a string in OCaml?
I made a comparison of the efficiency of different approaches:
I wrote a simple test:
let append_escaped s c = s ^ Char.escaped c let append_make s c = s ^ String.make 1 c let append_sprintf s c = Printf.sprintf "%s%c" s c let _ = let s = "some text" in let c = 'a' in for i = 1 to 100000000 do let _ = append_(*escaped|make|sprintf*) s c in () done
I compiled it natively (Intel Core 2 Duo).
I ran the test three times for each option, timing it with
time
, and calculating the mean real time elapsed.
Here are the results:
s ^ String.make 1 c
: 7.75s (100%)s ^ Char.escaped c
: 8.30s (107%)Printf.sprintf "%s%c" s c
: 68.57s (885%)
The code from @pad is what I would use, because I like to treat strings as immutable if possible. But I wouldn't use Char.escaped
; it's specialized for when you want the OCaml lexical representation of a character. So here's what you get if you make that change:
let prefix_char s c = String.make 1 c ^ s
let suffix_char s c = s ^ String.make 1 c
Update
In the years since this question was asked, OCaml has changed so that strings are immutable. Excellent.
String.make
and String.blit
is a good way to do so, but they seem to be imperative. Personally I prefer to make infix functions using Char.escaped
and string concatenation:
let (^$) c s = s ^ Char.escaped c (* append *)
let ($^) c s = Char.escaped c ^ s (* prepend *)