[erlang-questions] strip end off of string

Richard O'Keefe ok@REDACTED
Thu May 6 04:08:26 CEST 2010


On May 5, 2010, at 4:54 AM, Wes James wrote:

> I see that fist ++ rest below will match the first part of the string
> and the put the rest in "Rest":

The compiler can turn [E1,E2,E3]++Rest into [E1|[E2|[E3|Rest]]],
either in an expression context or a pattern context.
In the same way, it can turn "ABC"++Rest into [$A|[$B|[$C|Rest]]]
because "ABC" _is_ [$A,$B,$C].

> t2(First ++ "\">") ->
>      io:format("~s~n", [First]).

This, however, cannot be so transformed. If you understand how
lists work in Erlang (they are singly linked, with no stored
length), you will understand why it _obviously_ can't be so
transformed.

That doesn't mean that a compiler couldn't support this construct.
It would require special code (which "ABC"++_ does not), and above
all it requires building a whole new copy of First at run time
during pattern matching, while pattern matching is all about
taking things apart.

Binaries DO store a length, so something like
<<Rest/binary, "\">">> would be imaginable.

If you need to peel stuff off the end of a list, the simplest
way to do it is to reverse the list:

t2(String) ->
    t2a(lists:reverse(String)).

t2a(">\"" ++ Reversed) ->
     All_But_End = lists:reverse(Reversed),
     io:format("~s~n", [All_But_End]).

(By the way, "First" STRONGLY suggests "first element", which does
not apply here.  Prefix, or All_But_Last_Two, or Front, or something
which doesn't suggest an element, would be better.)

next thing people would be asking for Front++"ABC"++Back, which
doesn't have





More information about the erlang-questions mailing list