bug or feature?

Serge Aleynikov serge@REDACTED
Tue Apr 18 17:59:51 CEST 2006


It seems like for a previously bound Prefix, a compiler could add a 
is_list(Prefix) check, and convert Prefix ++ Suffix into a loop, failing 
with badarg if the first check fails.  I find this quite useful, as it 
would allow for doing things like:

strip_prefix(Prefix ++ Suffix, Prefix) ->
     Suffix;
strip_prefix(String) ->
     String.

instead of:

strip_prefix(String, Prefix) ->
     strip_prefix2(String, Prefix, String).
strip_prefix2(Suffix, [], _String) ->
     Suffix;
strip_prefix2([C | Tail], [C | PrefTail], String) ->
     strip_prefix2(Tail, PrefTail, String);
strip_prefix2(_, _, String) ->
     String.

There's no doubt that the first choice is much easier to read.

Regards,

Serge


Richard Carlsson wrote:
> Serge Aleynikov wrote:
> 
>> Could anyone explain why matches #5 and #6 below fail?  I didn't find 
>> in documentation a limitation of not being able to specify a variable 
>> as the first argument of the '++' transform.
>>
>> Eshell V5.4.13  (abort with ^G)
>> (a@REDACTED)5> Prefix ++ "100" = "200100".
>> ** 1: illegal pattern **
>> (a@REDACTED)6> Prefix ++ Suffix = "200100".
>> ** 1: illegal pattern **
> 
> 
> A pattern "fred" ++ Suffix is equivalent to [$f, $r, $e, $d | Suffix],
> which is easy to match on. For a pattern Prefix ++ Suffix, when Prefix
> is previously bound to some value (unknown at compile time), you could
> imagine the compiler generating code to perform the match as a loop
> (much like you'd match String = "foo" for a previously bound String)
> but there are some complications: what does it mean if Prefix turns out
> to be a non-list, or if it is not nil-terminated? Then, the pattern
> itself is illegal (just like the *expression* Prefix ++ Suffix). Should
> you get a "badarg" error instead of just a nonmatch? And if the pattern
> occurs in the second clause of a case, but the first clause matches,
> should you still get a badarg or not? The current limitation makes
> sure that patterns are always legal regardless of the runtime values.
> 
> (I'm not saying that it would not be convenient to have that kind of
> matching available, along with general regexps - it would, but it is
> not obvious that it can be made to fit in with the semantics of clause
> matching in Erlang, which has the advantage of predictability.)
> 
>     /Richard
> 
> 

-- 
Serge Aleynikov
R&D Telecom, IDT Corp.
Tel: (973) 438-3436
Fax: (973) 438-1464
serge@REDACTED



More information about the erlang-questions mailing list