How to convert char list to string in OCaml?
Asked Answered
W

4

8

I have a char list ['a';'b';'c']

How do I convert this to the string "abc"?

thanks x

Wisdom answered 30/4, 2015 at 1:17 Comment(0)
B
8

You can create a string of a length, equal to the length of the list, and then fold over the list, with a counter and initialize the string with the contents of the list... But, since OCaml 4.02, the string type started to shift in the direction of immutability (and became immutable in 4.06), you should start to treat strings, as an immutable data structure. So, let's try another solution. There is the Buffer module that is use specifically for the string building:

# let buf = Buffer.create 16;;
val buf : Buffer.t = <abstr>
# List.iter (Buffer.add_char buf) ['a'; 'b'; 'c'];;
- : unit = ()
# Buffer.contents buf;;
- : string = "abc"

Or, as a function:

let string_of_chars chars = 
  let buf = Buffer.create 16 in
  List.iter (Buffer.add_char buf) chars;
  Buffer.contents buf
Bigeye answered 30/4, 2015 at 1:30 Comment(0)
T
7

Since OCaml 4.07, you can use sequences to easily do that.

let l = ['a';'b';'c'] in
let s = String.of_seq (List.to_seq l) in
assert ( s = "abc" )
Tisiphone answered 30/11, 2020 at 14:14 Comment(0)
R
6
let cl2s cl = String.concat "" (List.map (String.make 1) cl)
Reunion answered 30/4, 2015 at 1:27 Comment(1)
This solution produces a stack overflow if the list is too long. In such cases, use ivg's solution. BTW, there's a String.of_list in batteries included.Martamartaban
E
1

Commonly used Base library also offers Base.String.of_char_list

Eric answered 29/11, 2020 at 21:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.