Browse thread
[Caml-list] Pattern matching and strings
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Sven LUTHER <luther@d...> |
| Subject: | Re: [Caml-list] Pattern matching and strings |
On Fri, Oct 04, 2002 at 02:00:37PM +0200, Andreas Rossberg wrote: > Sven Luther wrote: > > > > On Wed, Oct 02, 2002 at 04:12:34PM +0200, Alessandro Baretta wrote: > > > I have to do a little bit of pattern matching on strings. My > > > first instict was to write something like the following. > > > > > > let foo x = ... > > > let bar x = ... > > > ... = function > > > | "foo" ^ rest -> foo rest > > > | "bar" ^ rest -> bar rest > > > | _ -> raise Unrecognized > > > > What about : > > > > ... = function > > | str when String.sub str 0 3 = "foo" -> foo (String.sub str 2 (String.length str - 3)) > > | str when String.sub str 0 3 = "bar" -> bar (String.sub str 2 (String.length str - 3)) > > | _ -> raise Unrecognized > > > > Sure, this code is not very optimal, i guess you could write a nicer > > function which will test the string incrementally using just String.get > > or something such, but i suppose it will do the thing you want. > > The SML basis library provides the nice but often overlooked concept of > substrings (or more generally, vector slices, > http://SML.sourceforge.net/Basis/substring.html). Ported to Caml the > Substring module would enable > > > ... = function > > | s when Substring.is_prefix "foo" s -> foo (Substring.triml 3 s) > > | s when Substring.is_prefix "bar" s -> bar (Substring.triml 3 s) > > | _ -> raise Unrecognized > > where your parsing functions operate on substrings instead of strings. > Such an approach seems like a good compromise between use of a heavy > regexp lib and inefficient repeated copying of parts of strings. Well, like i said, it was just a quick implementation, but i am sure you can do this more or less optimaly with a hand coded String.get using comparison function. I don't know if you really can escape the use of the final copying of the string though. Friendly, Sven Luther ------------------- To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/ Beginner's list: http://groups.yahoo.com/group/ocaml_beginners