title: Counting in Erlang (how do I increment a variable?)
body: <p>I've figured out the Erlang-style loops: tail-recursion with functions that take all the "variables that don't vary":</p>
  
  <pre><code>%% does something, 80 bytes at a time
  loop(Line, File) -&gt; loop(Line, File, 0).
  loop(Line, File, Count) -&gt; 
      do_something(Line, Count),
      case file:read(File, 80) of
          {ok, Line2} -&gt; loop(Line2, File, Count + 1);
          eof -&gt; file:close(File);
          {error, Reason} -&gt; {error, Reason}
      end.
  </code></pre>
  
  <p>But, what is the best way to increment a counter in Erlang? In most programming languages, the way you count things is by incrementing a variable (ie. <code>count += 1;</code>). Erlang's variables don't vary, so we have to be creative. Fortunately, we have options...</p>
  
  <p>We can pass a Counter variable with our functions, and increment it with each function call. We can use the process dictionary to store a count, and <code>get</code> and <code>put</code> to increment it. We can use ETS, the local data storage for processes. We can use a counter process (!!!):</p>
  
  <pre><code>loop(Count) -&gt;                            
      receive                                   
          { incr } -&gt; 
              loop(Count + 1);              
          { report, To } -&gt;                     
              To ! { count, Count },            
              loop(Count)                           
      end.                                      
  
  incr(Counter) -&gt;
      Counter ! { incr }.
  
  get_count(Counter) -&gt;    
      Counter ! { report, self() },
      receive
          { count, Count } -&gt; Count
      end.
  </code></pre>
  
  <p>I'm sure there are other ways too, depending on the scope. What's considered "best practice" for incrementing a variable in Erlang?</p>