【问题标题】:yaws and erlang beam files in ebinebin 中的 yaws 和 erlang 梁文件
【发布时间】:2010-12-06 20:46:27
【问题描述】:

当我的表单帖子中有整数和浮点数并在我有梁文件的 ebin 文件中接收这些时,我遇到了问题。希望有人可以帮助我。

npower.yaws

   <erl>
kv(K,L) ->
{value, {K, V}} = lists:keysearch(K,1,L), V.        
out(A) ->
L = yaws_api:parse_post(A),
N = kv("number", L),
    npower62:math3(N).
    </erl>

npower62.erl 编译成束文件
-模块(npower62)。
-导出([math3/1])。

math3( [N] ) ->
数字 = N,
Nsquare = 数字 * 数字,
{html, io_lib:format("~c = ~w", [N, Nsquare])}.

给我 3 = 2601 的平方
而不是
3 = 9的平方
我曾尝试使用 Number = list_to_integer(atom_to_list(N))(不起作用)
我曾尝试使用 Number = list_to_float(atom_to_list(N))(不起作用)
我尝试使用 Number = list_to_integer(N) (不起作用)

【问题讨论】:

    标签: erlang floating-point integer yaws


    【解决方案1】:

    首先,您可以缩小math3/1 函数接受的范围:

    -module(npower62). 
    -export([math3/1]). 
    
    math3(N) when is_number(N) -> 
      N2 = N * N,
      io_lib:format("square of ~p = ~p", [N, N2]).
    

    请注意,我们已经对函数进行了相当多的重写。它不再接受列表,而是任何数字,仅限N。此外,您交给io_lib:format/2 的格式字符串完全关闭,请参阅man -erl io

    我们现在可以攻击 yaws 代码了:

    <erl>
      kv(K,L) ->
          proplists:get_value(K, L, none).
    
      out(A) ->
        L = yaws_api:parse_post(A),
        N = kv("number", L),
        none =/= N, %% Assert we actually got a value from the kv lookup
    
        %% Insert type mangling of N here so N is converted into an Integer I
        %% perhaps I = list_to_integer(N) will do. I don't know what type parse_post/1
        %% returns.
    
        {html, npower62:math3(I)}
    </erl>
    

    请注意,您的 kv/2 函数可以使用 proplists 查找函数编写。在您的代码变体中,从kv/2 返回的值是{value, {K, V}},在您的math3/1 版本中永远不会正确。 proplists:get_value/3 仅返回 V 部分。另请注意,我将 {html, ...} 提升到了这个级别。让 npower62 处理它是不好的风格,因为它不应该知道它是从 yaws 内部调用的事实。

    我的猜测是你需要调用 list_to_integer(N)。解决这个问题的最简单方法是调用 error_logger:info_report([{v, N}]) 并在 shell 或日志文件中查找 INFO REPORT 并查看术语 N 是什么。

    TL;DR:问题在于您的价值观并非在所有地方都匹配。因此,您将面临 yaws 可能会捕获、记录然后幸存下来的功能的无数崩溃。这会让你无所适从。

    另外,从 erl shell 测试您的函数 npower62:math3/1 函数。这样一来,您就会从一开始就发现它是错误的,从而减少您的困惑。

    【讨论】:

    • 工作得很好!!!你给出了很好的实用答案!但是如果输入的数字不是整数怎么办?如果它是一个浮点数怎么办?例如1.2?我们想要处理整数或浮点数的情况(在我们的 npower.yaws 文件中?
    • 我可能会使用string:to_floatstring:to_integer。诀窍是先测试整数,然后再尝试浮点数,如果有没有被解析的东西。
    • @IGIVECRAPANSWERS:none =/= N 不会断言你得到了值。 false none =:= Ntrue = none =/=N 会。
    猜你喜欢
    • 2011-09-14
    • 1970-01-01
    • 2014-07-16
    • 2015-03-30
    • 2015-05-04
    • 2012-07-24
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    相关资源
    最近更新 更多