【问题标题】:Why does Erlang think string module functions are undefined?为什么 Erlang 认为字符串模块函数是未定义的?
【发布时间】:2017-12-03 20:58:45
【问题描述】:

在学习 Erlang 的基础知识(特别是通过 this MOOC)时,我正在研究 Exercism Erlang 练习,目前我正在学习 Bob。在查阅了 Erlang 文档后,我编写了我认为应该是该问题的有效解决方案,但我遇到了运行时错误,我无法弄清楚究竟是什么导致了它,也不知道如何解决这个问题。我的代码编译得很好,并且是:

-module(bob).
-export([test_version/0,response_for/1]).

test_version() ->
    1.

response_for(Message) ->
    Trimmed = string:trim(Message),
    AllUpper = string:equal(Trimmed, string:uppercase(Trimmed)),
    Empty = string:is_empty(Trimmed),
    EndsWithQuestion = string:equal("?", lists:last(Trimmed)),
    if
        AllUpper -> "Whoa, chill out!";
        Empty -> "Fine. Be that way!";
        EndsWithQuestion -> "Sure.";
        true -> "Whatever."
    end.

您可以忽略 test_version 函数,它是您测试代码的单元测试的一部分,以检查您是否有正确的解决方案。单元测试可用here。我在每个功能测试中遇到的错误都是一样的,如下所示:

bob_tests: responds_to_something_test...失败在函数中 string:trim/1 在通话中称为 trim("Tom-ay-to, tom-aaaah-to.") 来自鲍勃:response_for/1 (c:/Users/jcoo092/exercism/erlang/bob/_build/test/lib/bob/src/bob.erl, 第 8 行)从 bob_tests 调用:'-bob_responds/2-fun-0-'/2 (c:/Users/jcoo092/exercism/erlang/bob/_build/test/lib/bob/test/bob_tests.erl, 第 71 行)来自 bob_tests:responds_to_something_test/0 的调用 **错误:undef 输出:>

我查看了 undef 错误的含义,显然这意味着 Erlang 运行时认为 string:trim() 函数未定义(第 8 行是 Trimmed = ... 行)。我试过跳过那个并继续其他人,但他们给出了同样的错误。显然我在这里做错了,因为这些函数在 Erlang 网站的文档中列出,但我真的看不出问题所在。

谁能解释我做错了什么,以及如何解决它?

【问题讨论】:

    标签: erlang


    【解决方案1】:

    Erlang/OTP 20 中执行你的代码,它确实给了我一个错误,但它不是你发布的那个。

    ** exception error: no function clause matching unicode_util:cp(46) (unicode_util.erl, line 285)
     in function  string:equal_1/2 (string.erl, line 508)
     in call from bob:response_for/1 (src/bob.erl, line 11)
    

    这是由于lists:last(Trimmed) 采用了 Trimmed 字符串的最后一个字符。这不是unicode:chardata() 类型,因为函数string:equal/2 要求两个参数都是。

    将其包含在列表中将解决上述问题:

     EndsWithQuestion = string:equal("?", [lists:last(Trimmed)]),
    

    【讨论】:

    • 啊,这就是问题所在!我没有意识到有一个新的主要版本的 Erlang 出来了。在发行说明中进行快速测试,看起来这些字符串函数很可能是第 20 版的新功能。我现在正在尝试更新我的 Erlang 安装,我猜这可能会解决它(然后给我您指出的另一个问题)。更新完成后我会在这里发表评论。
    • 原来这确实是问题所在。在 Erlang/OTP 20 上尝试它是有效的 - 然后给了我你发现的错误,你提出的修改很容易解决这个问题。谢谢! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    相关资源
    最近更新 更多