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

Daniel Dormont <>
Mon Jun 27 20:27:59 CEST 2011


On Jun 27, 2011, at 1:23 PM, Jachym Holecek wrote:

> # 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! :-)
> 

Right, fair enough.

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

I was not familiar with lists:suffix. I am now :) and it works fine for my purposes.

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

Ok.

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

Right, unfortunately in the place where my module will be called, the string values are in lists, not binaries.

> Or somesuch, you get the idea.
> 

Dan





More information about the erlang-questions mailing list