Erlang to switch (case) on divisibility

I want to use Erlang to determine if a variable passed to a function is divisible by a number. I've considered using case to do this but, the solution has eluded me. Is case the right tool for this job?

Example: pass a number to function f(). If the number is divisible by 10, print one statement. If it is divisible by 15, print a different statement. If it is divisible by 5 I think I want to print a third statement, but not the statement for 'divisible by 10' or 'divisible by 15' since the case has already been handled.

My intuition tells me case is right for this job, but I'm new to Erlang and am having trouble piecing it together.

Upvotes: 3

Views: 1216

Answers (1)

legoscia
legoscia

Reputation: 41528

You could do this with guards on your function clauses:

f(N) when N rem 10 =:= 0 ->
    io:format("divisible by 10~n");
f(N) when N rem 15 =:= 0 ->
    io:format("divisible by 15~n");
f(N) when N rem 5 =:= 0 ->
    io:format("divisible by 5~n").

Or you could do this with an if expression:

f(N) ->
    if N rem 10 =:= 0 ->
        io:format("divisible by 10~n");
       N rem 15 =:= 0 ->
        io:format("divisible by 15~n");
       N rem 5 =:= 0 ->
        io:format("divisible by 5~n")
    end.

If you're getting the number from somewhere else, it might be more natural to use a case expression:

f() ->
    case get_number() of
        N when N rem 10 =:= 0 ->
            io:format("divisible by 10~n");
        N when N rem 15 =:= 0 ->
            io:format("divisible by 15~n");
        N when N rem 5 =:= 0 ->
            io:format("divisible by 5~n")
    end.

Note that all of these expressions will crash if the number is not divisible by 5. This is often considered good style in Erlang: if your function cannot do anything sensible with bad input, it's better to let it crash and have the caller handle the error than to complicate your code with handling errors on every level. That depends on your specific requirements, of course.

Upvotes: 5

Related Questions