[erlang-questions] What is allowed in a pattern in terms of string concatenation?
Jachym Holecek
freza@REDACTED
Mon Jun 27 19:23:36 CEST 2011
# Daniel Dormont 2011-06-27:
> 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:
There are no strings in Erlang! :-)
> case string:substr(lists:reverse(String1), 1, length(String2)) of
> String2 -> ok;
> _ -> not_ok
> end
Kevin already pointed you to lists:suffix/2 which is good if suffix
isn't statically known, and very easy on the eyes too. If suffix is
known you could do:
has_suffix(L) ->
has_suffix2(lists:reverse(L)).
has_suffix2("xiffus" ++ _) ->
true;
has_suffix2(_) ->
false.
Which I think answers your other question. More precisely, AFAIU this
has_suffix2("xiffus" ++ _)
is just syntactic sugar for
has_suffix2([$x, $i, $f, $f, $u, $s | _])
So in a way you could perhaps say "++" isn't really supported in pattern
matching (but other will know this with more certainty). One doesn't see
"++" used very often overall, in my experience.
Also, this would have been so much cheaper (but harder to read) if you
used binaries to represent strings:
has_suffix(S, B) ->
has_suffix2(byte_size(B) - byte_size(S), S, B).
has_suffix2(N, _, _) when N < 0 ->
false;
has_suffix2(N, S, <<_:N/binary, D/binary>>) ->
S == D.
Or somesuch, you get the idea.
HTH,
-- Jachym
More information about the erlang-questions
mailing list