views:

199

answers:

2

To learn the basics of OCaml, I'm solving one of the easy facebook engineering puzzles using it. Essentially, I'd like to do something like the following Python code:

some_str = some_str.strip()

That is, I'd like to strip all of the whitespace from the beginning and the end. I don't see anything obvious to do this in the OCaml Str library. Is there any easy way to do this, or am I going to have to write some code to do it (which I wouldn't mind, but would prefer not to :) ).

Bear in mind that I'm limited to what's in the libraries that come with the OCaml distribution.

+3  A: 

how about

let trim str =   if str = "" then "" else   let search_pos init p next =
    let rec search i =
      if p i then raise(Failure "empty") else
      match str.[i] with
      | ' ' | '\n' | '\r' | '\t' -> search (next i)
      | _ -> i
    in
    search init   in   let len = String.length str in   try
    let left = search_pos 0 (fun i -> i >= len) (succ)
    and right = search_pos (len - 1) (fun i -> i < 0) (pred)
    in
    String.sub str left (right - left + 1)   with   | Failure "empty" -> "" ;;

(Via Code Codex)

TBH
+4  A: 

It is really a mistake to limit yourself to the standard library, since the standard ilbrary is missing a lot of things. If, for example, you were to use Core, you could simply do:

open Core.Std

let x = String.strip "  foobar   "
let () = assert (x = "foobar")

You can of course look at the sources of Core if you want to see the implementation. There is a similar function in ExtLib.

zrr
Perhaps I misspoke. The rules say: "You are not guaranteed any libraries or plugins beyond what is part of the language/interpreter itself." The distribution is INRIA OCaml. Does Core fall under that category?
Jason Baker
Core is not part of the standard library. It's a third-party library that extends the standard (like Extlib and Batteries). You can download it here: http://janestcapital.com/?q=node/13
Chris Conway