Programming Erlang, lib_misc:odds_and_evens2


odds_and_evens2(L) ->
      odds_and_evens_acc(L, [], []).
odds_and_evens_acc([H|T], Odds, Evens) ->
      case (H rem 2) of
           1  -> odds_and_evens_acc(T,  [H|Odds], Evens);
           0  -> odd_and_evens_acc(T, Odds, [H|Evens])
odds_and_evens_acc([], Odds, Evens) ->
      {Odds, Evens}.

This is from Kindle location 2235. Armstrong’s book. I’m reading 2nd Edition and this wasn’t, to my memory, in the first edition. I’m re-reading but there’s more in 2nd Edition. I thought it was important to really understand Erlang before jumping into Elixir.

Question is about the second line, where you see a period. What does that line DO then, with L, [], []?
I get the rest, just don’t see how this works with that second line. I didn’t see this question posted, obviously, and yes, I’m a noob to this. But with Elixir, at least it took like one minute to solve things like FizzBuzz and I feel retarded with anything BUT FP languages (imperative-style loops are my bane). I’d really appreciate explaining how this works with the second line in there.


Calls odds_and_evens_acc([H|T], Odds, Evens) with Odds and Evens as empty lists?

Then, in odds_and_evens_acc/3 it gets the head H (it is probably a number) of the given list L, and if it’s odd, it adds this head to the Odds list (it doesn’t actually add though, just calls the function again with a tail T and a new list for Odds), and if it’s even, it does the same but for the Evens list. This happens until the first argument to odds_and_evens_acc/3 becomes an empty list. You probably didn’t need this explanation …

It would probably look something like this in elixir, if that helps.

def odds_and_evens2(list), do: odds_and_evens_acc(list, [], [])

defp odds_and_evens_acc([head | tail], odds, evens) do
  case rem(head, 2) do
    1 -> odds_and_evens_acc(tail, [head | odds], evens)
    0 -> odds_and_evens_acc(tail, odds, [head | evens])
defp odds_and_evens_acc([], odds, evens), do: {odds, evens}


Okay, thanks, I get it. The period threw me off. It just sets up empty lists for odd and even, like you said. Thanks.


On Erlang’s Syntax

Another variant of this one has been suggested to me on #erlang. The user simply reads , as ‘and’, ; as ‘or’ and . as being done. A function declaration can then be read as a series of nested logical statements and affirmations.

Personally I go by:

  • , delimits a sequence of expressions
  • ; completes a (function, case, condition) clause
  • . completes a function