Is there something like list pattern matching in SML/NJ, but for strings? What I want to do eventually is to remove the first character of a string, if it's a specific one, and a solution of this kind came first to mind, so I would appreciate it if I could do it without further messing e.g. by turning the string into list form, and such.
Asked
Active
Viewed 2,410 times
2 Answers
4
Not directly. The most common way to solve this problem would be to get the caller of your function to split out the first character such that you can pattern match on it.
In SML'97, a string is a CharVector.vector (which has the signature MONO_VECTOR). SML/NJ does permit pattern matching on vectors (which is a non-standard extension), but unfortunately not on monomorphic vectors, as far as I can tell.

Gian
- 13,735
- 44
- 51
3
String.explode
will produce a list of characters from a string. Matching on the head of that list will produce the desired functionality:
fun f s =
let val c = hd(String.explode s)
in
case c
of #"a" => "The character is a!"
| #"b" => "The character is b!"
| #"c" => "The character is c!"
| _ => "Not a b or c!"
end
A list of characters suggests a string parsing state-machine approach rather than a Perl-like regex pattern match.

ben rudgers
- 3,647
- 2
- 20
- 32
-
Thanks for the answer. Your solution is practical, however the other answer was chosen because, being aware of explode, the main point of my question was whether a direct form of pattern matching for string existed or not. – Noob Doob Aug 08 '14 at 13:07
-
2@NoobDoob I understand that. My answer is for all thosepeople landing on the page from Google. They need something practical. SML documentation is already so opaque (e.g. assuming a working knowledge of C) for the introductory courses in which it is often used that the internet would just suck more for people trying to learn programming if the only answer was "No" and said "the reason as a strings are monomorphic vectors." [not that that's an acutal quote.] – ben rudgers Aug 08 '14 at 16:49