2010-09-16 76 views
4

以下shell會話顯示了一些行爲我想了解:字符串咬食匹配表達與結合的可變

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 

當然語句2和5是syntacticially相同?我希望使用這個習慣用法從字符串中提取一些文本,其中B正從配置文件讀入。這是可能的,我應該使用什麼語法來代替上面5)中所示的語法?

謝謝!

回答

4

LHS ++ RHS模式在編譯時擴展到[ lhs0, lhs1, lhs2 | RHS](其中LHS =:= [lhs0, lhs1, lhs2],編譯器拒絕任何東西,但文字字符串/列表做到這一點。從理論上講它可以變量做到這一點,但它根本不是現在。

我覺得你的情況,你需要做的:。

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

啊,語法糖樂趣感謝 – 2010-09-16 21:36:40

+0

編譯器在編譯時不能擴展的變量,因爲它不如何擴大他們。 – rvirding 2010-09-17 12:34:00

+1

可以想象通過擴展t來實現這種情況o當運行時匹配LHS時,運行時遍歷這兩個並行的列表,返回RHS尾部,否則不匹配類型的操作。 – archaelus 2010-09-17 20:43:51