[erlang-questions] What is allowed in a pattern in terms of string concatenation?

Daniel Dormont <>
Tue Jun 28 05:58:03 CEST 2011


On Mon, Jun 27, 2011 at 9:34 PM, Richard O'Keefe <> wrote:

>
> On 28/06/2011, at 3:52 AM, Daniel Dormont wrote:
>
> > Suppose I want to test that a certain string String1 ends with a certain
> other string String2. The best I could come up with is:
> >
> > case string:substr(lists:reverse(String1), 1, length(String2)) of
> >       String2 -> ok;
> >       _ -> not_ok
> > end
> >
> > I was thinking there must be a better way, but various attempts along the
> lines of
> >       case String1 of
> >               _ ++ String2 -> ok;
> >
> > all returned "illegal pattern" errors. I couldn't find a clear
> explanation online of when exactly ++ is allowed in a pattern and when it's
> not, so I'm a bit stumped.
>
> Section 7.4 of the reference manual is the place where it says ++ is
> allowed
> as a pattern, and the only thing it allows on the left of ++ is an explicit
> string literal.  A pattern like
>        "foo"++X
> is just shorthand for
>        [$f,$o,$o|X]
>
>
I see. I'd found that section in my searching earlier, but hadn't made the
connection that it has to be literal (in my defense, the manual doesn't
exactly say that).


> If you want to check whether String1 ends with String2,
> (a) you're going to need an even number of calls to lists:reverse/1
> (b) you are going to be kicking yourself that you didn't read the
>    documentation for the 'lists' module
>        http://www.erlang.org/doc/man/lists.html
>    because
>        lists:suffix(String2, String1)
>    does exactly what you want (modulo returning 'true' or 'false').
>

Sometimes the challenge is not knowing where to look. I've used lists of
course, but Erlang's lists is a pretty big module; it's easy to miss a few
things here and there :)

Anyway, thanks.

dan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20110627/7e3d9dab/attachment.html>


More information about the erlang-questions mailing list