Some useful OCaml functions
Fall 2000, David Matuszek, Villanova University

OCaml has more convenient functions for working with lists than it does for strings. With this in mind, here are two functions for converting between strings and lists, and a filter-like function for lists that you may find useful.

(* Convert a string to a list of characters *)
let rec explode = function
    "" -> []
  | s  -> (String.get s 0) ::
          explode (String.sub s 1 ((String.length s) - 1));;

(* Convert a list of characters to a string *)  
let rec implode = function
    []       -> ""
  | charlist -> (Char.escaped (List.hd charlist)) ^
                (implode (List.tl charlist));;
  
(* Break list into two parts: those at the head of the
   list that satisfy the test, and all the rest *)
let rec prefix test list =
  if list = [] then ([], [])
  else if (test (List.hd list)) then
    let (first, second) = prefix test (List.tl list)
       in ((List.hd list)::first, second)
  else ([], list);;
Examples:
# explode "hello";;
- : char list = ['h'; 'e'; 'l'; 'l'; 'o']
# implode ['h'; 'e'; 'l'; 'l'; 'o'];;
- : string = "hello"
# let even n = n mod 2 = 0 in
  prefix even [2;4;8;5;6;3;10];;
  - : int list * int list = [2; 4; 8], [5; 6; 3; 10]