How do you append a char to a string in OCaml?

前端 未结 3 1156
伪装坚强ぢ
伪装坚强ぢ 2021-02-20 16:42

It seems as if there is no function in the standard library of type char -> string -> string, which insert a char in front of (or at the end of)

3条回答
  •  你的背包
    2021-02-20 17:17

    I made a comparison of the efficiency of different approaches:

    1. 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
      
    2. I compiled it natively (Intel Core 2 Duo).

    3. I ran the test three times for each option, timing it with time, and calculating the mean real time elapsed.

    Here are the results:

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

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

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

提交回复
热议问题