Question

Coming from a Lisp background, Erlang's case statement seems a bit baffling to me. I'm currently working on the Sieve of Eratosthenes problem, trying to generate a list of the prime factors of a number N. However I can't seem to migrate what seems like a simple cond statement in Lisp to the equivalent in Erlang.

So far I have constructed an if statement that resembles how I would go about things in Lisp:

prime_factors(N) -> pf_helper(N, [], 2).


pf_helper(M, PL, D) ->

if 

  prime_p(M) == true -> [ M | PL ];

  (prime_p(D) == true) and (M rem D == 0) -> pl_helper(M div D, [ D | PL ], D+1);

  (prime_p(D) == true) and (M rem D /= 0) -> pl_helper(M, PL, D+1);

  prime_p(D) == false -> pl_helper(M, PL, D+1)

end.

I am aware that this will not compile since I can only have BIF calls in my guards. The problem is that I cannot conceptualize how this would run as a case statement, since case handles a conditional expression on one argument. In the case that I represent the three pf_helper arguments in a tuple:

pf_helper(M,PL,D) -> pf_helper({M, PL, D}).

what would the patterns be inside the case statements that correspond to the conditional expressions

   prime_p(M) == true 

  (prime_p(D) == true) and (M rem D == 0) 

  (prime_p(D) == true) and (M rem D /= 0)

  prime_p(D) == false 

?

Was it helpful?

Solution

Use some guards:

case {prime_p(M), prime_p(D)} of
  {true, _} -> [M|PL];
  {false, true} when (M rem D == 0) -> ...;
  {false, true} when (M rem D /= 0) -> ...;
  {false, false} -> ...
end

I think Anthony Ramine was working on implementing cond at one point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top