Red
Red

Reputation: 115

Erlang - A function that returns how many of its 3 arguments are equal

I'm just starting on erlang and I have this class task to create a function that returns how many of its 3 arguments are equal. Example:

My solution to this is:

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

The code takes the arguments as a list then creates another list2 by remove any duplicates using usort.

A-B+1= number of duplicates. If A-B is 0 then stay 0.

This is my newbie way of solving this problem. What is the most elegant way of doing this?

Upvotes: 0

Views: 130

Answers (2)

7stud
7stud

Reputation: 48629

You can also use pattern matching in the head of the duplicates function:

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

In the 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> 

That is the kind of function definition that erlang is known for.

Upvotes: 3

choroba
choroba

Reputation: 242008

My newbie way would be

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

Upvotes: 1

Related Questions