代码之家  ›  专栏  ›  技术社区  ›  pandoragami

二郎:案例。。函数调用返回的构造?

  •  2
  • pandoragami  · 技术社区  · 13 年前

    代码生成的错误为

    2> X = "2".
    "2"
    3> case_:main(X).
    main 50
    sender 50
    ** exception error: bad argument
         in function  case_:sender/1 (case_.erl, line 14)
         in call from case_:main/1 (case_.erl, line 6)
    4> Z = 2.
    2
    5> case_:main(Z).
    ** exception error: bad argument
         in function  io:format/3
            called as io:format(<0.25.0>,"main ~p~n",2)
         in call from case_:main/1 (case_.erl, line 5)
    6> 
    

    在第一次尝试时,我试图传递一个字符串,这使它比第二次尝试传递整数要远得多。我不知道为什么这不起作用。

    函数调用 sender(Input) 应返回 {Data} 来自 receiver() 函数调用。

    我肯定需要程序中的消息传递部分,因为我正试图编写一个循环来接收消息、评估消息并返回结果;但也许 case...of 语句可能会被抛出。

    -module(case_).
    -export([main/1, sender/1, receiver/0]).
    
    main(Input) ->
        io:format("main ~p~n",Input),
        case sender(Input) of
            {Data} ->
                io:format("Received ~p~n",Data)
        end.
    
    sender(Input) ->
        io:format("sender ~p~n",Input),
        Ref = make_ref(),
        ?MODULE  ! { self(), Ref, {send_data, Input}},
        receive
            {Ref, ok, Data} ->
                {Data}      
        end.    
    
    receiver() ->
        io:format("receiver ~n"),
        receive
            {Pid, Ref, {send_data, Input}} ->
                Pid ! { Ref, ok, Input + Input} 
        end.
    
    1 回复  |  直到 13 年前
        1
  •  4
  •   troutwine    13 年前

    令人高兴的是,badarg修复很容易。 io:format/2 将术语列表作为第二个参数。请参阅:

    (Erlang R15B02 (erts-5.9.2) [source] [64-bit] [smp:8:8] [async-threads:0] [hipe] [kernel-poll:false]
    
    Eshell V5.9.2  (abort with ^G)
    1> io:format("main ~p~n", 2).
    ** exception error: bad argument
         in function  io:format/3
            called as io:format(<0.24.0>,"main ~p~n",2)
    2> io:format("main ~p~n", [2]).
    main 2
    ok
    

    你的第二个问题是 ?MODULE 只返回当前模块名称的一个原子。您将要将消息发送到进程。如果您将代码修改为这样:

    -module(case_).
    -export([main/1, sender/2, receiver/0]).
    
    main(Input) ->
        io:format("main ~p~n", [Input]),
        Recv = spawn(?MODULE, receiver, []),
        case sender(Recv, Input) of
            {Data} ->
                io:format("Received ~p~n", [Data])
        end.
    
    sender(Pid, Input) ->
        io:format("sender ~p~n", [Input]),
        Ref = make_ref(),
        Pid ! { self(), Ref, {send_data, Input}},
        receive
            {Ref, ok, Data} ->
                {Data}
        end.
    
    receiver() ->
        io:format("receiver ~n"),
        receive
            {Pid, Ref, {send_data, Input}} ->
                Pid ! { Ref, ok, Input + Input}
        end.
    

    那么repl中的交互作用:

    Erlang R15B02 (erts-5.9.2) [source] [64-bit] [smp:8:8] [async-threads:0] [hipe] [kernel-poll:false]
    
    Eshell V5.9.2  (abort with ^G)
    1> c("case_").
    {ok,case_}
    2> case_:main(2).
    main 2
    sender 2
    receiver 
    Received 4
    ok