Search code examples
ocaml

string to list of char


I want to write a function that taking a string and return a list of char. Here is a function, but I think it is not do what I want ( I want to take a string and return a list of characters).

let rec string_to_char_list s =
    match s with
      | "" -> []
      | n -> string_to_char_list n

Solution

  • Aside, but very important:

    Your code is obviously wrong because you have a recursive call for which all the parameters are the exact same one you got in. It is going to induce an infinite sequence of calls with the same values in, thus looping forever (a stack overflow won't happen in tail-rec position).


    The code that does what you want would be:

    let explode s =
      let rec exp i l =
        if i < 0 then l else exp (i - 1) (s.[i] :: l) in
      exp (String.length s - 1) []
    

    Source: http://caml.inria.fr/pub/old_caml_site/FAQ/FAQ_EXPERT-eng.html#strings


    Alternatively, you can choose to use a library: batteries String.to_list or extlib String.explode