erlang - erl 程序输出的值与 erlang shell 输出的值不同

标签 erlang erlang-shell erl

给定以下 erlang 函数

-module(fibonacci).

-export([my_function_3/1]).

my_function_3(Arg1) when Arg1==3 -> io:format("=3");
my_function_3(Arg1) when Arg1<3 -> io:format("<3");
my_function_3(Arg1) when Arg1>3 -> io:format(">3").

从命令行调用 my_function_3 函数显示的值与从 shell 调用它时显示的值不同(见下文)。

请注意,我使用 234 作为参数,以便在函数的所有定义中对函数进行求值。

erlang shell 调用 my_function_3

$ erl
Erlang/OTP 22 [erts-10.6.2] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe]

Eshell V10.6.2  (abort with ^G)
1> c(fibonacci).
{ok,fibonacci}
2> fibonacci:my_function_3(2).
<3ok
3> fibonacci:my_function_3(3).
=3ok
4> fibonacci:my_function_3(4).
>3ok

从命令行调用my_function_3

$ erlc fibonacci.erl
$ erl -noshell -s fibonacci my_function_3 2 -s init stop
>3%
$ erl -noshell -s fibonacci my_function_3 3 -s init stop
>3%
$ erl -noshell -s fibonacci my_function_3 4 -s init stop
>3%

因此,我的问题是:为什么从命令行调用函数和从 erlang shell 调用函数时,erlang 输出不同的值?

最佳答案

来自 docs :

-s Mod [Func [Arg1, Arg2, ...]](init flag)
Makes init call the specified function. Func defaults to start. If no arguments are provided, the function is assumed to be of arity 0. Otherwise it is assumed to be of arity 1, taking the list [Arg1,Arg2,...] as argument. All arguments are passed as atoms. See init(3).

  1. 因为这一行:

    If no arguments are provided, the function is assumed to be of arity 0. Otherwise it is assumed to be of arity 1, taking the list [Arg1,Arg2,...] as argument.

    您的函数将接收一个列表作为唯一的参数。

  2. 因为这一行:

    All arguments are passed as atoms.

    列表中的所有参数都将是原子。

因此,您需要选出列表的头部来获取唯一的参数,然后您必须将原子转换为整数,以便与另一个整数进行 == 比较。像这样:

-module(fib).
-export([my_function_3/1]).

my_function_3([Arg1|_Rest]) ->
    Arg1Int = list_to_integer(atom_to_list(Arg1)),
    print_result(Arg1Int).

print_result(Arg1) when Arg1<3 ->
    io:format("<3~n");
print_result(Arg1) when Arg1==3 ->
    io:format("=3~n");
print_result(Arg1) when Arg1>3 ->
    io:format(">3~n").

请注意,在 erlang 中,一个术语可以与任何类型的另一个术语进行比较,并且不会导致错误。这是因为在 erlang 中,所有类型都被赋予特定的顺序:

number < atom < reference < fun < port < pid < tuple < list < bit string

正如您所看到的,列表被认为大于数字,因此您的 Arg1(它是一个列表)始终被认为大于数字 3。

关于erlang - erl 程序输出的值与 erlang shell 输出的值不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60518518/

相关文章:

erlang - Erlang仿真器信息语句是什么意思?

functional-programming - Erlang:获取列表中每个元组的第一个元素

linux - ejabberd 'make' 到 "cannot run compiled C program"

erlang - 生产环境未找到 OTP 模块 :httpc when using exrm

c++ - 如何将 Erlang 连接到 C++?

c - 段错误后重启 Erlang 节点

erlang - 如何在 Erlang 中执行系统命令并使用 os :cmd/1? 获取结果

redis - 在数据库中存储 ejabberd 存在信息

json - 如何将元组列表转换为 Json 字符串

xml - 使用 tsung POST 请求发送 json