0

こんにちは、サンプルの erlang コードがあります。

%%file_comment
-module(helloworld).
%% ====================================================================
%% API functions
%% ====================================================================
-export([add/2,subtract/2,hello/0,greet_and_math/1]).
%% ====================================================================
%% Internal functions
%% ====================================================================
add(A,B)->
A+B.

subtract(A,B)->
io:format("SUBTRACT!~n"),
A-B.

hello()->
io:format("Hello, world!~n").

greet_and_math(X) ->
hello(),
subtract(X,3),
add(X,2).

そして、私が走るとき

helloworld:greet_and_math(15).

出力は次のとおりです。

こんにちは世界!

減算!

17

私の疑問は、15-2=13 である AB がコンソールに表示されないのはなぜですか?

4

2 に答える 2

2

それは、 15-2を印刷したことがないからです。必要なコードは次のようになります。

%%file_comment
-module(helloworld).
%% ====================================================================
%% API functions
%% ====================================================================
-export([add/2,subtract/2,hello/0,greet_and_math/1]).
%% ====================================================================
%% Internal functions
%% ====================================================================
add(A,B)->
A+B.

subtract(A,B)->
io:format("SUBTRACT!~n"),
io:format("~p~n", [A-B]).   % this will make sure A-B is printed to console

hello()->
io:format("Hello, world!~n").

greet_and_math(X) ->
hello(),
subtract(X,3),
add(X,2).

それはあなたに与えるでしょう:

Hello, world!
SUBTRACT!
12
17

なぜ17が出力されるのか不思議に思うなら、それは最後の式だからです。これは、コードによって実際に返されるものであるため、コードの実行後に常にコンソールに出力されます。コンソールで実行するio:format("hello~n").と、次のように表示されます。

hello
ok

okこの場合は によって返されio:format、最後の式であるため、出力されます。

io:format("hello~n"),
io:format("world~n").

結果は次のとおりです。

hello
world
ok

コンソールで確認できるのは、秒単位で最後okに返されたものだけです。 これがどのように機能するかについて理解していただければ幸いです。io:format

したがって、あなたの場合は次のように入力します。

4> A = helloworld:greet_and_math(15).
Hello, world!
SUBTRACT!
17
5> A.
17
6> 

最後の式なので、17によって返される値がどのようになっているかわかりますか? greet_and_math(15)したがって、変数に割り当てることができます。

于 2013-09-18T11:23:15.957 に答える