How to add char to string in OCaml?

It seems that in the standard library like char -> string -> string there is no function that inserts a char before (or at the end) a string . Possible workarounds, for example. using String.make or String.blit . Is there an elegant way to do this?

+8
string char ocaml
source share
3 answers

String.make and String.blit are a good way to do this, but they seem imperative. Personally, I prefer to make infix functions using Char.escaped and string concatenation:

 let (^$) cs = s ^ Char.escaped c (* append *) let ($^) cs = Char.escaped c ^ s (* prepend *) 
+6
source share

The code from @pad is what I will use because I like to treat strings as immutable, if possible. But I would not use Char.escaped ; he specializes in when you want the vocabulary representation of an OCaml character. So here is what you get if you make this change:

 let prefix_char sc = String.make 1 c ^ s let suffix_char sc = s ^ String.make 1 c 
+16
source share

I compared the effectiveness of different approaches:

  • I wrote a simple test:

     let append_escaped sc = s ^ Char.escaped c let append_make sc = s ^ String.make 1 c let append_sprintf sc = Printf.sprintf "%s%c" sc let _ = let s = "some text" in let c = 'a' in for i = 1 to 100000000 do let _ = append_(*escaped|make|sprintf*) sc in () done 
  • I compiled it initially (Intel Core 2 Duo).

  • I ran the test three times for each option, running it using time and calculating the average time in real time.

Here are the results:

  • s ^ String.make 1 c : 7.75s ( 100% )

  • s ^ Char.escaped c : 8.30s ( 107% )

  • Printf.sprintf "%s%c" sc : 68.57s ( 885% )

+8
source share

All Articles