我有以下代码:
M =list:sort([X|Y]), list:sort(length) / 2,io:format("The median of the items is", [M]),
但是当我尝试编译它时会收到警告:
Warning: the result of the expression is ignored (suppress the warning by assigning the expression to the _ variable)
怎么了?我该如何解决?
这是我周围的代码,它是我的程序唯一的问题。其他一切都有效。
answer([ ]) -> io:format(" There are no items in the list");
answer([X|Y]) ->
M =list:sort([X|Y]), list:sort(length) / 2,io:format("The median of the items is", [M]),
答案 0 :(得分:2)
在您的代码中,list:sort(length)
将失败,因为length是一个原子且函数正在查找列表,而io:format/2
格式字符串缺少一个占位符来打印结果。
以下代码有效,至少它打印结果,但它总是返回ok。
answer([ ]) -> io:format("There are no items in the list~n");
answer(L) when is_list(L) -> io:format("The median of the items is ~p~n",
[lists:nth((length(L)+1) div 2,lists:sort(L))]);
answer(_) -> io:format("error,the input parameter is not a list~n").
直接在控制台中输入的一些使用示例。您可以看到,当列表包含除数字之外的其他元素时,它会给出一个看起来很奇怪的答案,虽然技术上是正确的。
1> Answer = fun([ ]) -> io:format("There are no items in the list~n");
1> (L) when is_list(L) -> io:format("The median of the items is ~p~n",
1> [lists:nth((length(L)+1) div 2,lists:sort(L))]);
1> (_) -> io:format("error,the input parameter is not a list~n") end.
#Fun<erl_eval.6.80484245>
2> L1 = [6,9,5,7,8].
[6,9,5,7,8]
3> Answer(L1).
The median of the items is 7
ok
4> L2 = [4,6,3].
[4,6,3]
5> Answer(L2).
The median of the items is 4
ok
6> L3 = [4,6,3,8].
[4,6,3,8]
7> Answer(L3).
The median of the items is 4
ok
8> L4 = [hello, 5,[1,2]].
[hello,5,[1,2]]
9> Answer(L4).
The median of the items is hello
ok
10> Answer("test_string").
The median of the items is 114
ok
11> Answer(test_atom).
error,the input parameter is not a list
ok
12> Answer("").
There are no items in the list
ok
13>