Erlang - returns 3 个参数中有多少个参数相等的函数
Erlang - A function that returns how many of its 3 arguments are equal
我刚开始使用 erlang,我有这个 class 任务来创建一个函数,returns 它的 3 个参数中有多少个参数相等。示例:
- countDuplicates(1,2,3) = 0
- countDuplicates(1,2,2) = 2
- countDuplicates(2,2,2) = 3
我的解决方案是:
- module(equals).
- export([Duplicates/3]).
Duplicates(X,Y,Z)->
List=[X,Y,Z],
A=length(List),
List2=lists:usort(List),
B=length(List2),
if
A-B==0 ->
0;
true ->
A-B+1
end.
该代码将参数作为一个列表,然后通过使用 usort 删除所有重复项来创建另一个 list2。
- A= 列表长度
- B= list2 的长度
A-B+1=重复数。
如果 A-B 为 0,则保持为 0。
这是我解决这个问题的新手方法。这样做最优雅的方法是什么?
我的新手方式是
countDuplicates(X, Y, Z) ->
if
X == Y andalso Y == Z ->
3;
X /= Y andalso Y /= Z andalso Z /= X ->
0;
true -> 2
end.
你也可以在duplicates函数的头部使用模式匹配:
-module(my).
-compile(export_all).
duplicates(N, N, N) -> 3;
duplicates(N, N, _) -> 2;
duplicates(N, _, N) -> 2;
duplicates(_, N, N) -> 2;
duplicates(_, _, _) -> 0.
duplicates_test() ->
0 = duplicates(1,2,3),
2 = duplicates(1,2,2),
2 = duplicates(2,2,1),
2 = duplicates(2,1,2),
3 = duplicates(2,2,2),
all_tests_passed.
在shell中:
~/erlang_programs$ erl
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V9.3 (abort with ^G)
1> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}
2> my:duplicates_test().
all_tests_passed
3>
这就是 erlang 所熟知的那种函数定义。
我刚开始使用 erlang,我有这个 class 任务来创建一个函数,returns 它的 3 个参数中有多少个参数相等。示例:
- countDuplicates(1,2,3) = 0
- countDuplicates(1,2,2) = 2
- countDuplicates(2,2,2) = 3
我的解决方案是:
- module(equals).
- export([Duplicates/3]).
Duplicates(X,Y,Z)->
List=[X,Y,Z],
A=length(List),
List2=lists:usort(List),
B=length(List2),
if
A-B==0 ->
0;
true ->
A-B+1
end.
该代码将参数作为一个列表,然后通过使用 usort 删除所有重复项来创建另一个 list2。
- A= 列表长度
- B= list2 的长度
A-B+1=重复数。 如果 A-B 为 0,则保持为 0。
这是我解决这个问题的新手方法。这样做最优雅的方法是什么?
我的新手方式是
countDuplicates(X, Y, Z) ->
if
X == Y andalso Y == Z ->
3;
X /= Y andalso Y /= Z andalso Z /= X ->
0;
true -> 2
end.
你也可以在duplicates函数的头部使用模式匹配:
-module(my).
-compile(export_all).
duplicates(N, N, N) -> 3;
duplicates(N, N, _) -> 2;
duplicates(N, _, N) -> 2;
duplicates(_, N, N) -> 2;
duplicates(_, _, _) -> 0.
duplicates_test() ->
0 = duplicates(1,2,3),
2 = duplicates(1,2,2),
2 = duplicates(2,2,1),
2 = duplicates(2,1,2),
3 = duplicates(2,2,2),
all_tests_passed.
在shell中:
~/erlang_programs$ erl
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V9.3 (abort with ^G)
1> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}
2> my:duplicates_test().
all_tests_passed
3>
这就是 erlang 所熟知的那种函数定义。