tag:blogger.com,1999:blog-2701628522441228496.post-43573586594752212272007-10-04T20:17:00.000-07:002007-10-04T20:19:05.187-07:00Reading SICP in Erlang: Section 1.1.4<p>Ok, here&#8217;s my erlang take on Section 1.1.4 of <span class="caps">SICP</span>, or you can go look at my <a href="http://on-ruby.blogspot.com/2007/10/reading-sicp-in-factor-section-114.html">Ruby</a> or <a href="http://on-ruby.blogspot.com/2007/10/reading-sicp-in-ruby-114.html">Factor</a> versions.</p><br /><br /><br /> <p>Unlike Scheme, Ruby, or Factor, I&#8217;ve got to put the code for the <tt>square</tt> and <tt>sum_of_squares</tt> functions<sup><a href="#fn1">1</a></sup> into a separate file. I&#8217;m not going to explain the mechanics of the file, but we can take a look at the functions themselves.</p><br /><br /><br /><pre><strong>sicp.erl</strong><br /><code> -module(sicp).<br /> -export([square/1]).<br /> -export([sum_of_squares/2]).<br /> square(A) -&gt; A * A.<br /> sum_of_squares(A, B) -&gt; sicp:square(A) + sicp:square(B).<br /></code></pre><br /><br /> <p><tt>square</tt> has an arity of 1 (it takes a single argument), and returns the value of that argument times itself. Because mulitplication only works with numeric types, it will work for integers and floats, but will fail for non-numeric arguments.</p><br /><br /><br /> <p>To execute these functions we need to compile the code (see line 1 below). Then we just call the function (with its module namespace) and give it an appropriate argument.</p><br /><br /><br /><pre><code><br />1&gt; c(sicp).<br />{ok,sicp}<br />2&gt; sicp:square(5).<br />25<br />3&gt; sicp:sum_of_squares(3,4).<br />25<br /></code></pre><br /><br /> <p>And that&#8217;s about all there is to it. Pretty simple stuff. Next up will be section 1.1.6 exercise 1.3.</p><br /><br /><br /> <p id="fn1"><sup>1</sup> In <span class="caps">SICP</span> they&#8217;re called procedures; in Ruby, methods; and in Factor, words. I just need to try to keep them all straight.</p>patehttp://www.blogger.com/profile/10492341480170667775noreply@blogger.com