Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert char list to string in OCaml?

Tags:

list

char

ocaml

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

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

thanks x

like image 941
Aditya Agrawal Avatar asked Apr 30 '15 01:04

Aditya Agrawal


2 Answers

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
like image 84
ivg Avatar answered Nov 15 '22 11:11

ivg


let cl2s cl = String.concat "" (List.map (String.make 1) cl)
like image 44
Jeffrey Scofield Avatar answered Nov 15 '22 09:11

Jeffrey Scofield