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

Richard O'Keefe <>
Tue Jun 28 03:34:47 CEST 2011


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]

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').





More information about the erlang-questions mailing list