As of OCaml 4.07 (released 2018), this can be straightforwardly accomplished with sequences.
let string_to_char_list s =
s |> String.to_seq |> List.of_seq
It may help to see an implementation of creating a sequence for a string. In the standard library, this is done by way of the bytes type, but we can implement a simple function to do the same directly with a string.
let string_to_seq s =
let len = String.length s in
let rec aux i () =
if i = len then Seq.Nil
else Seq.Cons (s.[i], aux @@ i + 1)
in
aux 0
Or using exceptions:
let string_to_seq s =
let rec aux i () =
match String.get s i with
| ch -> Seq.Cons (ch, aux @@ i + 1)
| exception Invalid_argument _ -> Seq.Nil
in
aux 0
We can avoid the nested inner function if we provide a start index argument with a default value of 0
.
let rec string_to_seq ?(i=0) s () =
match String.get s i with
| ch -> Seq.Cons (ch, string_to_seq ~i: (i+1) s)
| exception Invalid_argument _ -> Seq.Nil
This lets us call simply string_to_seq "hello world"
but also to specify an initial starting sequence great than 0
.
| n -> string_to_char_list n
that's an infinite loop for you. Never recurse with the same parameter you got in! – Francisco