[back]

Split by Whitespace

Implement the function

val split_by_ws' : string -> string list

so that split_by_ws' s is the list of contiguous non-whitespace substrings of s, in the order in which they appear.

For this version of the problem, you may work with strings as lists of characters, using the functions explode and implode to convert between strings and character lists.

let explode (s : string) : char list =
  let rec loop acc i =
    if i = String.length s
    then acc
    else loop (s.[i] :: acc) (i + 1)
  in List.rev (loop [] 0)

let implode (l : char list) : string =
  String.init (List.length l) (List.nth l)

Examples

let _ = assert (split_by_ws' "1 23 + -94  *" = ["1"; "23"; "+"; "-94"; "*"])
let _ = assert (split_by_ws' "  foo    bar  \n\n   baz   " = ["foo"; "bar"; "baz"])