【问题标题】:Erlang - A function that returns how many of its 3 arguments are equalErlang - 一个返回其 3 个参数中有多少相等的函数
【发布时间】:2019-01-25 14:33:24
【问题描述】:

我刚开始学习 erlang,我有这个类任务来创建一个函数,该函数返回它的 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。

这是我解决这个问题的新手方法。这样做最优雅的方法是什么?

【问题讨论】:

  • 不能以大写字母 D 调用 Duplicates 的函数。
  • 第一个case是0还是1? :)
  • 您需要处理缩进,应该是 4 个空格,而不是 3 个空格。并且函数体内的 if 表达式需要缩进。

标签: erlang


【解决方案1】:

您还可以在重复函数的头部使用模式匹配:

-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.

在外壳中:

~/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 众所周知的那种函数定义。

【讨论】:

    【解决方案2】:

    我的新手方式是

    countDuplicates(X, Y, Z) ->
        if
            X == Y andalso Y == Z ->
                3;
            X /= Y andalso Y /= Z andalso Z /= X ->
                0;
            true -> 2
        end.
    

    【讨论】:

    • 在erlang中,推荐的函数名样式是snake_case:count_duplicates
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2012-12-14
    • 2020-08-11
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    相关资源
    最近更新 更多