【问题标题】:String chomping match expression with bound variable带有绑定变量的字符串chomping匹配表达式
【发布时间】:2011-04-13 10:41:54
【问题描述】:

以下 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 在语法上是相同的吗?我想使用这个习惯用法从字符串中提取一些文本,其中B 是从配置文件中读取的。这可能吗?我应该使用什么语法来代替上面 5) 中显示的语法?

谢谢!

【问题讨论】:

    标签: string erlang pattern-matching design-patterns


    【解决方案1】:

    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.
    

    【讨论】:

    • 啊,语法糖的乐趣!谢谢。
    • 编译器无法在编译时扩展变量,因为它不知道如何扩展它们。
    • 可以想象实现这种情况,扩展为一个runtime traverse-the-two-lists-in-parallel,当匹配的LHS用完时返回RHS tail,否则不匹配那种操作.
    • @archaelus 介意在bugs.erlang.org 打开功能请求吗?我很乐意备份它并帮助在运行时获得这种行为!
    猜你喜欢
    • 2016-10-22
    • 2020-05-14
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    相关资源
    最近更新 更多