How to evaluate the first element of a tuple ONLY if elements in the tuple are identical in Erlang?

Viewed 48

Let's say our Variable Five is a tuple of five elements. How do we write an expression that evaluates to (and prints) the first element, but only if all five elements are identical?

For example, given this following tuple:

Five = {4, 4, 4, 4, 4}.

I'm trying to use element(_,_). Statement as:

element(1, Five) =:= element(2, Five).

But this only give me the evaluation of the first element VS the 2nd one, not all together. Any idea how I can evaluate the first one with all the other elements the same time? { .................. } = Five, ....................

1 Answers

If you know the size of the tuple (e.g. 5 as in your example), you could pattern match using the same variable:

case Five of
    {X, X, X, X, X} -> io:format("~w", [X]), X;
    _Otherwise -> ok
end

Of course, the same can be done in function clauses.

If the size of the tuple is unknown, one way would be to convert it to a list using tuple_to_list/1 and, for example, use lists:all/2:

[H | T] = tuple_to_list(Five),
IsSame = lists:all(fun (E) -> E =:= H end, T),
case IsSame of
    true  -> io:format("~w", [H]), H;
    false -> ok
end
Related