Browse thread
[Caml-list] Pattern matching and strings
-
Alessandro Baretta
- Chris Hecker
-
Sven Luther
- Andreas Rossberg
[
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: | Andreas Rossberg <rossberg@p...> |
| Subject: | Re: [Caml-list] Pattern matching and strings |
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. -- Andreas Rossberg, rossberg@ps.uni-sb.de "Computer games don't affect kids; I mean if Pac Man affected us as kids, we would all be running around in darkened rooms, munching magic pills, and listening to repetitive electronic music." - Kristian Wilson, Nintendo Inc. ------------------- 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