views:

52

answers:

1

Hi,

The following shell sessions shows some behavior I would like to understand:

1> A = "Some text".
"Some text"
2> "Some " ++ R = A.
"Some text"
3> R.
"text"
4> B = "Some ".
"Some "
5> B ++ L = A.
* 1: illegal pattern

Surely statements 2 and 5 are syntacticially identical? I would like to use this idiom to extract some text from a string, where B is being read in from a configuration file. Is this possible, and what syntax should I use instead of that shown in 5) above?

Thanks!

+3  A: 

The LHS ++ RHS pattern is expanded at compiletime to [ lhs0, lhs1, lhs2 | RHS] (where LHS =:= [lhs0, lhs1, lhs2], and the compiler refuses to do this for anything but literal strings/lists. In theory it could do this for variables, but it simply doesn't right now.

I think in your case you need to do:

Prefix = read_from_config(),
TestString = "Some test string",
case lists:prefix(Prefix, TestString) of
    true ->
        %% remove prefix from target string
        lists:nthtail(length(Prefix), TestString);
    false ->
        different_prefix
end.
archaelus
Ah, the joys of syntactic sugar! Thanks.
James Jackson
The compiler can't expand variables at compiletime as it doesn't how to expand them.
rvirding
One can imagine implementing this case by expanding to a runtime traverse-the-two-lists-in-parallel, return RHS tail when you run out of matching LHS, otherwise don't match kind of operation.
archaelus