<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Ruslan's Blog &#187; erlang</title>
	<atom:link href="http://ruslanspivak.com/category/erlang/feed/" rel="self" type="application/rss+xml" />
	<link>http://ruslanspivak.com</link>
	<description>Musings on dynamic languages and more than that</description>
	<lastBuildDate>Wed, 02 Jun 2010 19:16:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='ruslanspivak.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/04a636b5f08c182c190ff6d8ae67239e?s=96&#038;d=http://s2.wp.com/i/buttonw-com.png</url>
		<title>Ruslan's Blog &#187; erlang</title>
		<link>http://ruslanspivak.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://ruslanspivak.com/osd.xml" title="Ruslan&#039;s Blog" />
	<atom:link rel='hub' href='http://ruslanspivak.com/?pushpress=hub'/>
		<item>
		<title>Array module in Erlang</title>
		<link>http://ruslanspivak.com/2008/04/13/array-module-in-erlang/</link>
		<comments>http://ruslanspivak.com/2008/04/13/array-module-in-erlang/#comments</comments>
		<pubDate>Mon, 14 Apr 2008 03:47:14 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[erlang]]></category>

		<guid isPermaLink="false">http://ruslanspivak.wordpress.com/?p=28</guid>
		<description><![CDATA[Recent Erlang releases (since R12B) have array module included. Now binary search algorithm can be implemented quite efficiently with functional arrays: -module(bsa). -export([binsearch/2]). binsearch(Arr, Key) -&#62; binsearch(Arr, Key, 0, array:size(Arr)). binsearch(Arr, Key, LowerBound, UpperBound) -&#62; Mid = (LowerBound + UpperBound) div 2, Item = array:get(Mid, Arr), if UpperBound &#60; LowerBound -&#62; -1; Key &#60; Item [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=28&subd=ruslanspivak&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>Recent Erlang releases (since R12B) have <a href="http://www.erlang.org/doc/man/array.html">array module</a> included.</p>
<p>Now <a href="http://ruslanspivak.com/2007/08/15/my-erlang-binary-search/">binary search</a> algorithm can be implemented quite  <a href="http://ruslanspivak.com/2007/08/17/more-about-binary-search-in-erlang/">efficiently</a> with functional arrays:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(bsa).
<span style="color:#87cefa;">-export</span>([binsearch/2]).

<span style="color:#87cefa;">binsearch</span>(<span style="color:#eedd82;">Arr</span>, <span style="color:#eedd82;">Key</span>) -&gt;
    binsearch(<span style="color:#eedd82;">Arr</span>, <span style="color:#eedd82;">Key</span>, 0, array:<span style="color:#00ffff;">size</span>(<span style="color:#eedd82;">Arr</span>)).

<span style="color:#87cefa;">binsearch</span>(<span style="color:#eedd82;">Arr</span>, <span style="color:#eedd82;">Key</span>, <span style="color:#eedd82;">LowerBound</span>, <span style="color:#eedd82;">UpperBound</span>) -&gt;
    <span style="color:#eedd82;">Mid</span> = (<span style="color:#eedd82;">LowerBound</span> + <span style="color:#eedd82;">UpperBound</span>) div 2,
    <span style="color:#eedd82;">Item</span> = array:<span style="color:#00ffff;">get</span>(<span style="color:#eedd82;">Mid</span>, <span style="color:#eedd82;">Arr</span>),
    <span style="color:#00ffff;">if</span>
        <span style="color:#eedd82;">UpperBound</span> &lt; <span style="color:#eedd82;">LowerBound</span> -&gt;<span style="color:#87cefa;"> </span>-1;
        <span style="color:#eedd82;">Key</span> &lt; <span style="color:#eedd82;">Item</span> -&gt;
            binsearch(<span style="color:#eedd82;">Arr</span>, <span style="color:#eedd82;">Key</span>, <span style="color:#eedd82;">LowerBound</span>, <span style="color:#eedd82;">Mid</span>-1);
        <span style="color:#eedd82;">Key</span> &gt; <span style="color:#eedd82;">Item</span> -&gt;
            binsearch(<span style="color:#eedd82;">Arr</span>, <span style="color:#eedd82;">Key</span>, <span style="color:#eedd82;">Mid</span>+1, <span style="color:#eedd82;">UpperBound</span>);
        true -&gt;
            <span style="color:#eedd82;">Mid</span>
    <span style="color:#00ffff;">end</span>.
</pre>
<p>Running time for <em>lists based</em> binary search (just for comparison):</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;"><span style="color:#00ffff;">56&gt; </span><span style="font-weight:bold;">{Time, Val} = timer:tc(search, binsearch,</span>
<span style="color:#00ffff;">56&gt; </span><span style="font-weight:bold;">                       [lists:seq(1, 1000000), 1000000]).</span>
{506513,  1000000}</pre>
<p>Running time for <em>array based</em> binary search:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;"><span style="color:#00ffff;">57&gt; </span><span style="font-weight:bold;">f().</span>
ok
<span style="color:#00ffff;">58&gt; </span><span style="font-weight:bold;">{Time, Val} = timer:tc(bsa, binsearch,</span>
<span style="color:#00ffff;">58&gt; </span><span style="font-weight:bold;">              [array:from_list(lists:seq(1, 1000000)), 1000000]).</span>
{17,  999999}</pre>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ruslanspivak.wordpress.com/28/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ruslanspivak.wordpress.com/28/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ruslanspivak.wordpress.com/28/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ruslanspivak.wordpress.com/28/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ruslanspivak.wordpress.com/28/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ruslanspivak.wordpress.com/28/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ruslanspivak.wordpress.com/28/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ruslanspivak.wordpress.com/28/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ruslanspivak.wordpress.com/28/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ruslanspivak.wordpress.com/28/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ruslanspivak.wordpress.com/28/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ruslanspivak.wordpress.com/28/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=28&subd=ruslanspivak&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2008/04/13/array-module-in-erlang/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4d73d92d1e35b86c5c45667b7a036da3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">alienoid</media:title>
		</media:content>
	</item>
		<item>
		<title>Erlang for Python programmers: Part V</title>
		<link>http://ruslanspivak.com/2007/11/16/erlang-for-python-programmers-part-v/</link>
		<comments>http://ruslanspivak.com/2007/11/16/erlang-for-python-programmers-part-v/#comments</comments>
		<pubDate>Fri, 16 Nov 2007 05:18:50 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/11/16/erlang-for-python-programmers-part-v/</guid>
		<description><![CDATA[Previous parts: Intro, Part I, Part II, Part III and Part IV List comprehensions. List comprehensions is very familiar topic for Python programmer. It&#8217;s a syntactic sugar which provides a succinct notation for producing elements in list. Erlang: [Expr &#124;&#124; Qualifier1,...,QualifierN] Expr &#8211; is an arbitrary expression Qualifier is either a generator or a filter. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=20&subd=ruslanspivak&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>Previous parts: <a href="http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/">Intro</a>, <a href="http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/">Part I</a>, <a href="http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/">Part II</a>, <a href="http://ruslanspivak.com/2007/09/24/erlang-for-python-programmers-part-iii/">Part III</a> and <a href="http://ruslanspivak.com/2007/10/02/erlang-for-python-programmers-part-iv/">Part IV</a></p>
<h3>List comprehensions.</h3>
<p>List comprehensions is very familiar topic for Python programmer. It&#8217;s a syntactic sugar which provides a succinct notation for producing elements in list.</p>
<h4><u><strong>Erlang:</strong></u></h4>
<pre>[Expr || Qualifier1,...,QualifierN]</pre>
<p><u><em>Expr</em></u> &#8211; is an arbitrary expression<br />
<u><em>Qualifier</em></u> is either a <strong>generator</strong> or a <strong>filter</strong>.<br />
A <strong>generator</strong> is of form <code>Pattern &lt;- ListExpr </code> where <em>ListExpr</em> evaluates to a list of terms.<br />
A <strong>filter</strong> expression should evaluate to <em>true</em> or <em>false.</em></p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">[X || X &lt;- [1,2,3,4,5,6], X &gt; 3].</span>
[4,5,6]</pre>
<p>This is read as: list of X such that X is taken from list [1,2,3,4,5,6] and X is greater than 3.</p>
<p>In foregoing example: <u><em>X &lt;- [1,2,3,4,5,6]</em></u> is a <strong>generator</strong> and <em><u>X &gt; 3</u></em> is a <strong>filter</strong>.</p>
<p>Several filters can be combined:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">[X || X &lt;- [1,a,2,3,b,4,5,6], X &gt; 3].</span>
[a,b,4,5,6]
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">[X || X &lt;- [1,a,2,3,b,4,5,6], integer(X), X &gt; 3].</span>
[4,5,6]</pre>
<p>Generator part may act as a filter in list comprehension:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">[X || {X, a} &lt;- [{1, a}, {2, b}, {3, a}, erlang]].</span>
[1,3]</pre>
<p>Generators can be combined too in list comprehensions. This is the Cartesian product of two lists:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">5&gt; </span><span style="font-weight:bold;">[{X, Y} || X &lt;- [1, 2, 3], Y &lt;- [a, b]].</span>
[{1,a},{1,b},{2,a},{2,b},{3,a},{3,b}]</pre>
<p>This is how elegantly quicksort algorithm is solved with the help of list comprehensions in Erlang:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(sort).
<span style="color:#87cefa;">-export</span>([qsort/1]).

<span style="color:#87cefa;">qsort</span>([]) -&gt;<span style="color:#87cefa;"> </span>[];
<span style="color:#87cefa;">qsort</span>([<span style="color:#eedd82;">Pivot</span>|<span style="color:#eedd82;">Tail</span>]) -&gt;
    qsort([<span style="color:#eedd82;">X</span> || <span style="color:#eedd82;">X</span> &lt;- <span style="color:#eedd82;">Tail</span>, <span style="color:#eedd82;">X</span> &lt; <span style="color:#eedd82;">Pivot</span>])
        ++ [<span style="color:#eedd82;">Pivot</span>] ++
        qsort([<span style="color:#eedd82;">X</span> || <span style="color:#eedd82;">X</span> &lt;- <span style="color:#eedd82;">Tail</span>, <span style="color:#eedd82;">X</span> &gt;= <span style="color:#eedd82;">Pivot</span>]).</pre>
<p>Compile and run:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">6&gt; </span><span style="font-weight:bold;">c("/home/alienoid/dev/erlang/sort", [{outdir, "/home/alienoid/dev/erlang/"}]).</span>
{ok,sort}
<span style="color:#00ffff;">7&gt; </span><span style="font-weight:bold;">sort:qsort([7, 5, 9, 3, 6]).</span>
[3,5,6,7,9]</pre>
<p>Usage of list comprehensions instead of some higher-order functions:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">8&gt; </span><span style="font-weight:bold;">lists:map(fun(X) -&gt; X*2 end, [1, 2, 3]).</span>
[2,4,6]
<span style="color:#00ffff;">9&gt; </span><span style="font-weight:bold;">[X*2 || X &lt;- [1, 2, 3]].</span>
[2,4,6]</pre>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">10&gt; </span><span style="font-weight:bold;">lists:filter(fun(X) -&gt; X rem 2 == 0 end, [1, 2, 3, 4]).</span>
[2,4]
<span style="color:#00ffff;">11&gt; </span><span style="font-weight:bold;">[X || X &lt;- [1, 2, 3, 4], X rem 2 == 0].</span>
[2,4]</pre>
<h4><u>Python:</u></h4>
<pre><strong>[</strong>expression <strong>for</strong> expr1 <strong>in</strong> seq1 <strong>if</strong> cond1
            <strong>for</strong> expr2 <strong>in</strong> seq2 <strong>if</strong> cond2
            <strong>for</strong> exprN <strong>in</strong> seqN <strong>if</strong> condN<strong>]</strong></pre>
<p>this actually transforms to:</p>
<pre>
for expr1 in seq1:
    if not cond1:
        continue
    for expr2 in seq2:
        if not cond2:
            continue
        for exprN in seqN:
            if not condN:
                continue</pre>
<p>So in Python Cartesian product of two lists <em>[1, 2, 3 ]</em> and <em>['a', 'b']</em> will look like:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">[(x, y) for x in [1, 2, 3] for y in ['a', 'b']]</span>
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]</pre>
<h4><u>Variable bindings and scope rules in List Comprehensions:</u></h4>
<p>Current Python 2.x &#8220;leaks&#8221; loop variable into surrounding scope. This should be solved in Python 3.0</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x</span>
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
<span style="color:#87cefa;">NameError</span>: name 'x' is not defined
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">vlist = [x for x in 'abc']</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">vlist</span>
['a', 'b', 'c']
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x</span>
'c'</pre>
<p>To avoid leaking loop variable into surrounding scope we can use generator expression which doesn&#8217;t &#8220;leak&#8221;:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">vlist = list(x for x in 'abc')</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">vlist</span>
['a', 'b', 'c']
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x</span>
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
<span style="color:#87cefa;">NameError</span>: name 'x' is not defined</pre>
<p>Erlang has following scope rules for variables in list comprehensions(from Erlang manual):</p>
<ul>
<li> all variables which occur in a generator pattern are         assumed to be &#8220;fresh&#8221; variables</li>
<li> any variables which are defined before the list         comprehension and which are used in filters have the values         they had before the list comprehension</li>
<li> no variables may be exported from a list comprehension</li>
</ul>
<p>So, Erlang doesn&#8217;t &#8220;leak&#8221; variables:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">[X || X &lt;- [1, 2, 3]].</span>
[1,2,3]
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">X.</span>
** 1: variable 'X' is unbound **</pre>
<p>Be careful, sometimes you need to move some pattern matching operations into filter:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(listcomp).
<span style="color:#87cefa;">-export</span>([select/2]).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">This select produces following warning during compilation:
</span><span style="color:#ff4500;">%% </span><span style="color:#ff4500;">Warning: variable 'X' shadowed in generate
</span><span style="color:#87cefa;">select</span>(<span style="color:#eedd82;">X</span>, <span style="color:#eedd82;">List</span>) -&gt;
    [<span style="color:#eedd82;">Y</span> || {<span style="color:#eedd82;">X</span>, <span style="color:#eedd82;">Y</span>} &lt;- <span style="color:#eedd82;">List</span>].</pre>
<p>The function doesn&#8217;t produce desired result:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">listcomp:select(b, [{b, 1}, {c, 2}, {b, 3}]).</span>
[1,2,3]</pre>
<p>So we modify generator and move pattern matching operation into filter to achieve what we need:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(listcomp).
<span style="color:#87cefa;">-export</span>([select/2]).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">Moving X from pattern matching into filter
</span><span style="color:#87cefa;">select</span>(<span style="color:#eedd82;">X</span>, <span style="color:#eedd82;">List</span>) -&gt;
    [<span style="color:#eedd82;">Y</span> || {<span style="color:#eedd82;">X1</span>, <span style="color:#eedd82;">Y</span>} &lt;- <span style="color:#eedd82;">List</span>, <span style="color:#eedd82;">X</span> == <span style="color:#eedd82;">X1</span>].</pre>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">listcomp:select(b, [{b, 1}, {c, 2}, {b, 3}]).</span>
[1,3]</pre>
<p>As you saw, while different in syntax, both languages provide valuable language construct which allows to write shorter and more elegant programs.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ruslanspivak.wordpress.com/20/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ruslanspivak.wordpress.com/20/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ruslanspivak.wordpress.com/20/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ruslanspivak.wordpress.com/20/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ruslanspivak.wordpress.com/20/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ruslanspivak.wordpress.com/20/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ruslanspivak.wordpress.com/20/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ruslanspivak.wordpress.com/20/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ruslanspivak.wordpress.com/20/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ruslanspivak.wordpress.com/20/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ruslanspivak.wordpress.com/20/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ruslanspivak.wordpress.com/20/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=20&subd=ruslanspivak&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/11/16/erlang-for-python-programmers-part-v/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4d73d92d1e35b86c5c45667b7a036da3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">alienoid</media:title>
		</media:content>
	</item>
		<item>
		<title>Erlang for Python programmers: Part IV</title>
		<link>http://ruslanspivak.com/2007/10/02/erlang-for-python-programmers-part-iv/</link>
		<comments>http://ruslanspivak.com/2007/10/02/erlang-for-python-programmers-part-iv/#comments</comments>
		<pubDate>Tue, 02 Oct 2007 16:17:49 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/10/02/erlang-for-python-programmers-part-iv/</guid>
		<description><![CDATA[Previous parts: Intro, Part I, Part II and Part III Funs &#8211; sequel Continuing previous post about functions let&#8217;s remember about Fun. I already mentioned it in Part I and promised to show its advanced forms. So, here we go. Fun with one clause: 1&#62; Double = fun(X) -&#62; X * 2 end. #Fun&#60;erl_eval.6.56006484&#62; 2&#62; [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=16&subd=ruslanspivak&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>Previous parts: <a href="http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/">Intro</a>, <a href="http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/">Part I</a>, <a href="http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/">Part II</a> and <a href="http://ruslanspivak.com/2007/09/24/erlang-for-python-programmers-part-iii/">Part III</a></p>
<h3>Funs &#8211; sequel</h3>
<p>Continuing previous post about functions let&#8217;s remember about <strong>Fun</strong>. I already mentioned it in <a href="http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/">Part I</a> and promised to show its advanced forms. So, here we go.</p>
<p><strong>Fun</strong> with one <strong>clause</strong>:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">Double = fun(X) -&gt; X * 2 end.</span>
#Fun&lt;erl_eval.6.56006484&gt;
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">Double(2).</span>
4</pre>
<p>But <strong>Fun</strong> actually has the same <a href="http://ruslanspivak.com/2007/09/24/erlang-for-python-programmers-part-iii/">function declaration syntax as regular function</a>, except that it has no name in declaration, so we can have this:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">Big = fun (X) when X &gt; 100 -&gt; true;</span>
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">          (X) -&gt; false</span>
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">      end.</span>
#Fun&lt;erl_eval.6.56006484&gt;
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">lists:filter(Big, [20, 30, 120, 130]).</span>
[120,130]</pre>
<p>As you see our <strong>Fun</strong> has <strong>two clauses</strong> separated by <strong>semicolon(;)</strong> and first clause has also <strong>guard</strong>, ie syntax is the same as in regular function declaration.</p>
<p>There are also following fun expressions that can be used:</p>
<ol>
<li><strong>fun FunctionName/Arity</strong> (<em>FunctionName</em> should point to local function defined in the same module with our <strong>fun</strong>)</li>
<li><strong>fun Module:FunctionName/Arity</strong> (<em>FunctionName</em> should be exported from module <em>Module</em>)</li>
</ol>
<p><strong>fun FunctionName/Arity</strong> is just <em>syntactic sugar </em>for <strong>fun (X1, ..Xn) -&gt; FunctionName(X1, .., Xn) end.</strong></p>
<p>Let&#8217;s take a look on foregoing in action and create <em>mymath.erl</em></p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([test1/0,
         test2/0,
         test3/0,
         double/1]).

<span style="color:#87cefa;">test1</span>() -&gt;<span style="color:#87cefa;"> </span>lists:map(<span style="color:#00ffff;">fun</span>(<span style="color:#eedd82;">X</span>) -&gt;<span style="color:#87cefa;"> </span><span style="color:#eedd82;">X</span> * 2 <span style="color:#00ffff;">end</span>, [1, 2, 3]).

<span style="color:#87cefa;">test2</span>() -&gt;<span style="color:#87cefa;"> </span>lists:map(<span style="color:#00ffff;">fun</span> double_local/1, [1, 2, 3]).

<span style="color:#87cefa;">test3</span>() -&gt;<span style="color:#87cefa;"> </span>lists:map(<span style="color:#00ffff;">fun</span> mymath:double/1, [1, 2, 3]).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">helper function, not exported
</span><span style="color:#87cefa;">double_local</span>(<span style="color:#eedd82;">X</span>) -&gt;
    <span style="color:#eedd82;">X</span> * 2.

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">helper function, exported
</span><span style="color:#87cefa;">double</span>(<span style="color:#eedd82;">X</span>) -&gt;
    <span style="color:#eedd82;">X</span> * 2.</pre>
<p>Compile and test it (I&#8217;m compiling as usual in Emacs with <strong>C-c C-k</strong>):</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">c("/home/alienoid/dev/erlang/mymath", [{outdir, "/home/alienoid/dev/erlang/"}]).</span>
{ok,mymath}
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">mymath:test1().</span>
[2,4,6]
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">mymath:test2().</span>
[2,4,6]
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">mymath:test3().</span>
[2,4,6]</pre>
<p>Also <strong>tuple of type {Module, FunctionName}</strong> is interpreted as a <strong>fun Module:FunctionName/Arity</strong> which you already saw. This usage is deprecated, but to be complete here is an example:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">5&gt; </span><span style="font-weight:bold;">Append = {lists, append}.</span>
{lists,append}
<span style="color:#00ffff;">6&gt; </span><span style="font-weight:bold;">Append([1, 2], [3, 4, 5]).</span>
[1,2,3,4,5]</pre>
<p>As you already noted <strong>Fun</strong> in Erlang is <em>&#8220;richer&#8221;</em> than <strong>lambda</strong> in Python.</p>
<h3> Built-in functions, BIFs</h3>
<p>Both Erlang and Python provide built-in functions that are always available and do not require explicit usage of module name to use them.</p>
<p><u>Python:</u></p>
<p>Read more about builtins in <a href="http://docs.python.org/lib/builtin.html">library reference</a>.</p>
<p>In Python shell you can inspect in addition contents of __builtins__ module if you need:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">import pprint</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">pprint.pprint(dir(__builtins__))</span>
['ArithmeticError',
 'AssertionError',
 ...
 'type',
 'unichr',
 'unicode',
 'vars',
 'xrange',
 'zip']</pre>
<p><u>Erlang:</u><br />
Most of the built-in functions belong to module <em>erlang</em> and they are <strong>auto-imported</strong>.<br />
To get list of all BIFs with description read <em>man erlang</em>.<br />
In Eshell you can get list of functions that belong to <em>erlang</em> module with <strong>m(Module).</strong> command:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">m(erlang).</span>
Module erlang compiled: No compile time info available
Compiler options:  []
Object file: preloaded
<span style="color:#87cefa;">Exports</span>:
'!'/2                         list_to_existing_atom/1
'$erase'/1                    list_to_float/1
'$erase'/0                    list_to_integer/2
'$get'/1                      list_to_integer/1
'$get'/0                      list_to_pid/1
'$get_keys'/1                 list_to_tuple/1
'$put'/2                      load_module/2
'*'/2                         loaded/0
'+'/1                         localtime/0
'+'/2                         localtime_to_universaltime/1
'++'/2                        localtime_to_universaltime/2
...
ok</pre>
<p>Take into account though that not all functions in above list that you&#8217;ll see are auto-imported and may require usage of <em>module:</em> prefix. Again, for more information read <em>man erlang</em> (either in command line with <strong>erl -man erlang</strong> or if you use Emacs take a look at <a href="http://ruslanspivak.com/2007/08/19/erlang-man-pages-in-emacs/">Erlang man pages in Emacs</a>)</p>
<h3>Macros</h3>
<p>Python does not have them, Erlang does. In Erlang they are not as powerful as in <a href="http://www.gigamonkeys.com/book/macros-defining-your-own.html">Common Lisp</a>, but more like in C.</p>
<p>They are defined in following form:</p>
<pre><strong>-define(Const, Replacement).
-define(Func(Var1,...,VarN), Replacement).</strong></pre>
<p>Whenever erlang preprocessor encounters expression of form <strong>?MacroName</strong> it expands corresponding macro.<br />
Define <em>utils.erl</em>:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(utils).
<span style="color:#87cefa;">-export</span>([foo/0]).
<span style="color:#87cefa;">-define</span>(<span style="color:#7fffd4;">TIMEOUT</span>, 100).
<span style="color:#87cefa;">-define</span>(<span style="color:#7fffd4;">FUNCMACRO</span>(<span style="color:#eedd82;">X</span>, <span style="color:#eedd82;">Y</span>), {<span style="color:#eedd82;">X</span>, x, <span style="color:#eedd82;">Y</span>, y}).

<span style="color:#87cefa;">foo</span>() -&gt;
    io:format(<span style="color:#ffa07a;">"TIMEOUT = ~p~n"</span>, [?<span style="color:#7fffd4;">TIMEOUT</span>]),
    ?<span style="color:#7fffd4;">FUNCMACRO</span>(3, 7).</pre>
<p>Compile and run:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">utils:foo().</span>
TIMEOUT = 100
{3,x,7,y}</pre>
<p>There are also some predefined macros:</p>
<dl>
<dt> <strong><code>?MODULE</code></strong> </dt>
<dd> The name of the current module. </dd>
<dt> <strong><code>?MODULE_STRING</code></strong>. </dt>
<dd> The name of the current module as a string. </dd>
<dt> <strong><code>?FILE</code></strong>. </dt>
<dd> The file name of the current module. </dd>
<dt> <strong><code>?LINE</code></strong>. </dt>
<dd> The current line number. </dd>
<dt> <strong><code>?MACHINE</code></strong>. </dt>
<dd> The machine name, <code>'BEAM'</code>.</dd>
</dl>
<p>Having <strong>?MODULE</strong> we can rewrite earlier example with <strong>Fun</strong> as:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([test1/0,
         test2/0,
         test3/0,
         double/1]).

<span style="color:#87cefa;">test1</span>() -&gt;<span style="color:#87cefa;"> </span>lists:map(<span style="color:#00ffff;">fun</span>(<span style="color:#eedd82;">X</span>) -&gt;<span style="color:#87cefa;"> </span><span style="color:#eedd82;">X</span> * 2 <span style="color:#00ffff;">end</span>, [1, 2, 3]).

<span style="color:#87cefa;">test2</span>() -&gt;<span style="color:#87cefa;"> </span>lists:map(<span style="color:#00ffff;">fun</span> double_local/1, [1, 2, 3]).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">test3() -&gt; lists:map(fun mymath:double/1, [1, 2, 3]).
</span><span style="color:#87cefa;">test3</span>() -&gt;<span style="color:#87cefa;"> </span>lists:map(<span style="color:#00ffff;">fun</span> ?<span style="color:#7fffd4;">MODULE</span>:double/1, [1, 2, 3]).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">helper function, not exported
</span><span style="color:#87cefa;">double_local</span>(<span style="color:#eedd82;">X</span>) -&gt;
    <span style="color:#eedd82;">X</span> * 2.

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">helper function, exported
</span><span style="color:#87cefa;">double</span>(<span style="color:#eedd82;">X</span>) -&gt;
    <span style="color:#eedd82;">X</span> * 2.</pre>
<p>And as usual compile and run to see that result is the same:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">c("/home/alienoid/dev/erlang/mymath", [{outdir, "/home/alienoid/dev/erlang/"}]).</span>
{ok,mymath}
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;"> mymath:test1().</span>
[2,4,6]
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;"> mymath:test2().</span>
[2,4,6]
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;"> mymath:test3().</span>
[2,4,6]</pre>
<p>In addition there is also <strong>flow control</strong> in macros. Some of corresponding macro directives are:</p>
<ul>
<li><strong>ifdef(Macro).</strong> &#8211; Evaluate the following lines only if <em>Macro</em> is defined.</li>
<li><strong>else.</strong> &#8211; It&#8217;s used after <em>ifdef</em> or <em>ifndef</em></li>
<li><strong>endif. </strong>- Marks the end of <em>ifdef</em> or <em>ifndef</em> directive</li>
</ul>
<p>Example in <em>utils.erl</em>:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(utils).
<span style="color:#87cefa;">-export</span>([foo/0]).

<span style="color:#87cefa;">-ifdef</span>(<span style="color:#7fffd4;">debug</span>).
<span style="color:#87cefa;">-define</span>(<span style="color:#7fffd4;">LOG</span>(<span style="color:#eedd82;">Msg</span>), io:format(<span style="color:#ffa07a;">"{~p:~p}: ~p~n"</span>, [?<span style="color:#7fffd4;">MODULE</span>, ?<span style="color:#7fffd4;">LINE</span>, <span style="color:#eedd82;">Msg</span>])).
<span style="color:#87cefa;">-else</span>.
<span style="color:#87cefa;">-define</span>(<span style="color:#7fffd4;">LOG</span>(<span style="color:#eedd82;">Msg</span>), true).
<span style="color:#87cefa;">-endif</span>.

<span style="color:#87cefa;">foo</span>() -&gt;
    ?<span style="color:#7fffd4;">LOG</span>(<span style="color:#ffa07a;">"Debug is enabled"</span>).</pre>
<p>To turn LOG macro on <em>debug</em> should be defined. This can be achieved from command line with <strong>erlc -Ddebug utils.erl</strong> or from Eshell using <strong>c/2</strong> function:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">c(utils, {d, debug}).</span>
{ok,utils}
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">utils:foo().</span>
{utils:11}: "Debug is enabled"
ok</pre>
<p>To turn LOG macro off <em>debug</em> should be omitted:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">c(utils).</span>
{ok,utils}
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">utils:foo().</span>
true</pre>
<p>To be continued.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ruslanspivak.wordpress.com/16/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ruslanspivak.wordpress.com/16/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ruslanspivak.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ruslanspivak.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ruslanspivak.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ruslanspivak.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ruslanspivak.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ruslanspivak.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ruslanspivak.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ruslanspivak.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ruslanspivak.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ruslanspivak.wordpress.com/16/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=16&subd=ruslanspivak&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/10/02/erlang-for-python-programmers-part-iv/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4d73d92d1e35b86c5c45667b7a036da3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">alienoid</media:title>
		</media:content>
	</item>
		<item>
		<title>Erlang for Python programmers: Part III</title>
		<link>http://ruslanspivak.com/2007/09/24/erlang-for-python-programmers-part-iii/</link>
		<comments>http://ruslanspivak.com/2007/09/24/erlang-for-python-programmers-part-iii/#comments</comments>
		<pubDate>Sun, 23 Sep 2007 23:53:50 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/09/24/erlang-for-python-programmers-part-iii/</guid>
		<description><![CDATA[Previous parts: Intro, Part I and Part II Today we are going to take a look at functions. In Erlang there is no direct correspondence to what we have in Python: 1. default values, keyword arguments and formal parameter of form **name def foo(key, name='ruslan', type='unknown', **kw): print 'key = %s, name = %s, type [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=14&subd=ruslanspivak&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>Previous parts: <a href="http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/">Intro</a>, <a href="http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/">Part I</a> and <a href="http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/">Part II</a></p>
<p>Today we are going to take a look at functions.<br />
In Erlang there is no direct correspondence to what we have in Python:</p>
<p>1. default values, keyword arguments and formal parameter of form <strong>**name</strong></p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">foo</span>(key, name=<span style="color:#ffa07a;">'ruslan'</span>, type=<span style="color:#ffa07a;">'unknown'</span>, **kw):
    <span style="color:#00ffff;">print</span> <span style="color:#ffa07a;">'key = %s, name = %s, type = %s'</span> % (key, name, type)
    <span style="color:#00ffff;">for</span> key, val <span style="color:#00ffff;">in</span> kw.items():
        <span style="color:#00ffff;">print</span> <span style="color:#ffa07a;">'%s = %s'</span> % (key, val)</pre>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">foo(1)</span>
key = 1, name = ruslan, type = unknown
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">foo(1, type='known', x=1, y=10)</span>
key = 1, name = ruslan, type = known
y = 10
x = 1</pre>
<p>2. formal parameter of form <strong>*name</strong></p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">double_sum</span>(*args):
    <span style="color:#00ffff;">return</span> sum(x * 2 <span style="color:#00ffff;">for</span> x <span style="color:#00ffff;">in</span> args)</pre>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">double_sum(2, 4, 5)</span>
22</pre>
<p>Let&#8217;s take a look at Erlang&#8217;s <u><em>function declaration syntax</em> (</u>a bit modified from Erlang Reference Manual):</p>
<ol>
<li><strong>Function declaration</strong> consists of function <strong>clauses</strong> separated by <strong>semicolons (;) </strong>and terminated by <strong>period (.)</strong></li>
<li><strong>Function clause</strong> consists of <strong>head</strong> and <strong>body</strong> separated by <strong>-&gt;</strong></li>
<li>A <strong>clause head</strong> consists of <em>function name</em> (which is atom), <em>argument list</em>(each argument is <strong>pattern</strong>) and optional <strong>guard sequence</strong> beginning with keyword <strong>when</strong>.</li>
<li>A <strong>clause body</strong> consists of sequence of expressions separated by <strong>comma (,)</strong></li>
</ol>
<h4>Name(Pattern11,&#8230;,Pattern1N) [when GuardSeq1] -&gt;<br />
Body1;<br />
&#8230;;<br />
Name(PatternK1,&#8230;,PatternKN) [when GuardSeqK] -&gt;<br />
BodyK.</h4>
<h4></h4>
<h4>where Body is in form:<br />
Expr1,<br />
Expr2,<br />
&#8230;<br />
ExprN</h4>
<p>Number of arguments in function is called <strong>arity</strong>. Function is uniquely identified by combination of <u><em>module name</em></u>, <u><em>function name</em></u> and <u><em>function&#8217;s arity</em></u> and this form is often written as <strong>m:f/N</strong>. Two functions in the module with the same name, but different arity<br />
are completely different functions, remember it.</p>
<p>Enough dry theory, let&#8217;s define our Erlang <em>factorial</em> function in module <em>mymath.erl</em> :</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([factorial/1]).

<span style="color:#87cefa;">factorial</span>(0) -&gt;
    1;
<span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">N</span>) -&gt;
    <span style="color:#eedd82;">N</span> * factorial(<span style="color:#eedd82;">N</span>-1).</pre>
<p>What we have here:</p>
<p>1) <strong>function declaration</strong> of one function called  <em>factorial</em><br />
2) there are two <strong>clauses</strong><br />
- first clause separated by <strong>semicolon (;)</strong></p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">factorial</span>(0) -&gt;
    1;</pre>
<p>- second and final clause terminated with <strong>period (.)</strong></p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">N</span>) -&gt;
    <span style="color:#eedd82;">N</span> * factorial(<span style="color:#eedd82;">N</span>-1).</pre>
<p>3) Every clause (first and second) has correspondingly head and body. Head consists of function&#8217;s name, in our case it&#8217;s <u>factorial</u> and after follows arguments list which contains patterns. In first clause pattern is <strong>0</strong>, in second &#8211; <strong>N</strong>.</p>
<p>How this works:</p>
<p>When function is entered, the function clauses are pattern matched against passed arguments. Pattern matching happens in order functions are defined in module. So when you enter</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">mymath:factorial(5).</span>
120</pre>
<p>first <strong>5</strong> is matched against clause <strong>factorial(0)</strong> and fails as <strong>5 != 0</strong>, then <strong>5</strong> is matched against <strong>N</strong> in second clause and pattern matching succeeds. As a result unbound variable <strong>N</strong> in pattern becomes bound and gets value <strong>5</strong>. This leads to execution of body of second clause, namely<strong> N * factorial(N-1)</strong>. This happens recursively until <strong>N</strong> becomes <strong>0</strong> and first clause<strong> factorial(0)</strong> is executed terminating recursion.<br />
The same <em>factorial</em> function will look in Python without pattern matching like:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">factorial</span>(n):
    <span style="color:#00ffff;">if</span> n == 0:
        <span style="color:#00ffff;">return</span> 1
    <span style="color:#00ffff;">return</span> n * factorial(n-1)</pre>
<p>In Python&#8217;s version we &#8220;hardcoded&#8221; branching in function&#8217;s body.</p>
<p>The benefits of pattern matching are that when conditions inside function become complex you may do your job better and write less code using pattern matching and also if you have big function this may mean that you do not have to modify body of your function but to add another clause with corresponding pattern.</p>
<p>Earlier I mentioned that function clauses are pattern matched in order they are defined in module. For our function this is important. If we change order of clauses this will lead to problems, as the condition to terminate recursion never appear:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([factorial/1]).

<span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">N</span>) -&gt;
    <span style="color:#eedd82;">N</span> * factorial(<span style="color:#eedd82;">N</span>-1);
<span style="color:#87cefa;">factorial</span>(0) -&gt;
    1.</pre>
<p>When compiling we will get warning (use <strong>C-c C-k</strong> in Emacs or <strong>c(mymath).</strong> in Eshell to compile)</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">c("/home/alienoid/dev/erlang/mymath", [{outdir, "/home/alienoid/dev/erlang/"}]).</span>
<span style="color:#ffc0cb;font-weight:bold;text-decoration:underline;">/home/alienoid/dev/erlang/mymath.erl</span><span style="text-decoration:underline;">:</span><span style="color:#eedd82;text-decoration:underline;">6</span><span style="text-decoration:underline;">:</span><span style="text-decoration:underline;"> Warning</span>: this clause cannot match because a previous clause at line 4 always matches
{ok,mymath}</pre>
<p>indicating that second clause will never match, but still you can call the function (it will most likely to crash after eating all your available memory).</p>
<p>You can easily avoid that problem introducing <strong>guard</strong> that starts with keyword <strong>when</strong> in function clause&#8217;s head:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([factorial/1]).

<span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">N</span>) <span style="color:#00ffff;">when</span> <span style="color:#eedd82;">N</span> &gt; 0 -&gt;
    <span style="color:#eedd82;">N</span> * factorial(<span style="color:#eedd82;">N</span>-1);
<span style="color:#87cefa;">factorial</span>(0) -&gt;
    1.</pre>
<p>Now you can put those two clauses in any order you like. I should also add that if during pattern matching no matched function clause is found a <em>function_clause</em> run time error will occur:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">mymath:factorial(-4).</span>

=ERROR REPORT==== 24-Sep-2007::01:53:25 ===
Error in process &lt;0.29.0&gt; with exit value: {function_clause,[{mymath,factorial,[-4]},{erl_eval,do_apply,5},{shell,exprs,6},{shell,eval_loop,3}]}

** exited: {function_clause,[{mymath,factorial,[-4]},
                             {erl_eval,do_apply,5},
                             {shell,exprs,6},
                             {shell,eval_loop,3}]} **</pre>
<p>What is <strong>guard</strong> anyway ? Guards make pattern matching more powerful, they can be used to perform different tests and comparison operations on variables in a pattern as you could see.  You can have several <em>guard expressions</em> in clause separated by <strong>commans (,). </strong>The guard<strong> </strong>containing several guard expressions evaluates to <strong>true</strong> only if every guard expression evaluates to true. Example of guard containing several guard expressions:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([factorial/1]).

<span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">N</span>) <span style="color:#00ffff;">when</span> <span style="color:#7fffd4;">is_integer</span>(<span style="color:#eedd82;">N</span>), <span style="color:#eedd82;">N</span> &gt; 0 -&gt;
    <span style="color:#eedd82;">N</span> * factorial(<span style="color:#eedd82;">N</span>-1);
<span style="color:#87cefa;">factorial</span>(0) -&gt;
    1.</pre>
<p>For above definition calling <u>mymath:factorial(5)</u> reads as: <strong>choose clause factorial(N) when (N is integer AND N &gt; 0)</strong></p>
<p>There are also <strong>guard sequences</strong> which have form <strong>guard1; guard2; &#8230;; guardN</strong> and guard sequence evaluates to true if at least one guard is evaluated to true:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([factorial/1]).

<span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">N</span>) <span style="color:#00ffff;">when</span> <span style="color:#7fffd4;">is_integer</span>(<span style="color:#eedd82;">N</span>), <span style="color:#eedd82;">N</span> &gt; 0; <span style="color:#7fffd4;">is_list</span>(<span style="color:#eedd82;">N</span>) -&gt;
    <span style="color:#eedd82;">N</span> * factorial(<span style="color:#eedd82;">N</span>-1);
<span style="color:#87cefa;">factorial</span>(0) -&gt;
    1.</pre>
<p>For above definition calling <u>mymath:factorial(5)</u> reads as: <strong>choose clause factorial(N) when (N is integer AND N &gt; 0) OR N is list</strong>.</p>
<p>You have probably noted that the way we defined our factorial function means that it will be calling itself recursively and this will use stack and stack is not infinite resource. We need to do something about our function and this means to make it <strong>tail recursive</strong>. When last expression in function body is function call this means that call is <strong>tail recursive</strong> and this is how infinite loop may be done without consuming stack resources. So here is our new <strong>tail-recursive</strong> function <u><em>factorial</em></u> that uses accumulator to pass value of previous calculation:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([factorial/1]).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">this one is exported, arity is 1
</span><span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">N</span>) -&gt;
    factorial(<span style="color:#eedd82;">N</span>, 1).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">helper function, not exported, arity is 2
</span><span style="color:#ff4500;">%% </span><span style="color:#ff4500;">tail-recursive, uses accumulator to store
</span><span style="color:#ff4500;">%% </span><span style="color:#ff4500;">calculation between invocations
</span><span style="color:#87cefa;">factorial</span>(<span style="color:#eedd82;">N</span>, <span style="color:#eedd82;">Acc</span>) <span style="color:#00ffff;">when</span> <span style="color:#eedd82;">N</span> &gt; 0 -&gt;
    factorial(<span style="color:#eedd82;">N</span>-1, <span style="color:#eedd82;">N</span>*<span style="color:#eedd82;">Acc</span>);
<span style="color:#87cefa;">factorial</span>(0, <span style="color:#eedd82;">Acc</span>) -&gt;
    <span style="color:#eedd82;">Acc</span>.</pre>
<p>In foregoing example you can see guards, tail-recursion, usage of accumulators, functions with different arities. Experiment with it.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ruslanspivak.wordpress.com/14/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ruslanspivak.wordpress.com/14/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ruslanspivak.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ruslanspivak.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ruslanspivak.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ruslanspivak.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ruslanspivak.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ruslanspivak.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ruslanspivak.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ruslanspivak.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ruslanspivak.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ruslanspivak.wordpress.com/14/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=14&subd=ruslanspivak&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/09/24/erlang-for-python-programmers-part-iii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4d73d92d1e35b86c5c45667b7a036da3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">alienoid</media:title>
		</media:content>
	</item>
		<item>
		<title>comment-dwim and comment-style</title>
		<link>http://ruslanspivak.com/2007/09/20/comment-dwim-and-comment-style/</link>
		<comments>http://ruslanspivak.com/2007/09/20/comment-dwim-and-comment-style/#comments</comments>
		<pubDate>Thu, 20 Sep 2007 21:24:11 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/09/20/comment-dwim-and-comment-style/</guid>
		<description><![CDATA[In my previous post I mentioned that if you use Emacs and you&#8217;re editing Erlang source code you can easily comment whole marked region by invoking M-; to which by default bound interactive Lisp function comment-dwim. This works in different modes and it&#8217;s very handy especially if your language of choice has no multiline comments. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=13&subd=ruslanspivak&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/">previous post</a> I mentioned that if you use Emacs and you&#8217;re editing Erlang source code you can easily comment whole marked region by invoking <strong>M-;</strong> to which by default bound interactive Lisp function  <strong>comment-dwim</strong>. This works in different modes and it&#8217;s very handy especially if your language of choice has no multiline comments.</p>
<p>So far so good, but I must admit sometimes I get the blues when I comment some nested code blocks with <strong>M-;</strong> keystrokes. Well, maybe I&#8217;m blowing things out of proportion about my sadness, but in any case recently I came across really nice small blog post called <a href="http://edward.oconnor.cx/2007/09/comment-style">comment-style</a> and since then I&#8217;m happy with comments produced in nested blocks. Let&#8217;s see why.</p>
<p>When you comment marked regions in Emacs buffer with <strong>M-;</strong> the <strong>comment-style</strong> variable defines the way regions are commented.  Default value is <strong>plain</strong>.</p>
<p>Buffer with Python code before commenting:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">binsearch</span>(seq, key, start, end):
    <span style="color:#00ffff;">if</span> end &lt; start:
        <span style="color:#00ffff;">return</span> -1
    mid = (start + end) / 2
    <span style="color:#00ffff;">if</span> key == seq[mid]:
        <span style="color:#00ffff;">return</span> mid
    <span style="color:#00ffff;">if</span> key &lt; seq[mid]:
        <span style="color:#00ffff;">return</span> binsearch(seq, key, start, mid-1)
    <span style="color:#00ffff;">if</span> key &gt; seq[mid]:
        <span style="color:#00ffff;">return</span> binsearch(seq, key, start+1, end)</pre>
<p>Buffer with Python code after commenting:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">binsearch</span>(seq, key, start, end):
    <span style="color:#00ffff;">if</span> end &lt; start:
        <span style="color:#00ffff;">return</span> -1
    mid = (start + end) / 2
    <span style="color:#ff4500;"># if key == seq[mid]:
</span><span style="color:#ff4500;">#         </span><span style="color:#ff4500;">return mid
</span>    <span style="color:#00ffff;">if</span> key &lt; seq[mid]:
        <span style="color:#00ffff;">return</span> binsearch(seq, key, start, mid-1)
    <span style="color:#00ffff;">if</span> key &gt; seq[mid]:
        <span style="color:#00ffff;">return</span> binsearch(seq, key, start+1, end)</pre>
<p>As you see visually elements of commented block are not on the same line.</p>
<p>Example with Erlang code before commenting (somewhat far-fetched example though our main concern are comments, not code here):</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">all</span>(<span style="color:#eedd82;">Pred</span>, [<span style="color:#eedd82;">Hd</span>|<span style="color:#eedd82;">Tail</span>]) -&gt;
    <span style="color:#00ffff;">case</span> <span style="color:#eedd82;">Pred</span>(<span style="color:#eedd82;">Hd</span>) <span style="color:#00ffff;">of</span>
        true -&gt;<span style="color:#87cefa;"> </span>all(<span style="color:#eedd82;">Pred</span>, <span style="color:#eedd82;">Tail</span>);
        false -&gt;
            io:format(<span style="color:#ffa07a;">"Hd = ~p~n"</span>, [<span style="color:#eedd82;">Hd</span>]),
            true,
            false
    <span style="color:#00ffff;">end</span>;
<span style="color:#87cefa;">all</span>(<span style="color:#eedd82;">Pred</span>, []) <span style="color:#00ffff;">when</span> <span style="color:#7fffd4;">is_function</span>(<span style="color:#eedd82;">Pred</span>, 1) -&gt;<span style="color:#87cefa;"> </span>true.</pre>
<p>After commenting:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">all</span>(<span style="color:#eedd82;">Pred</span>, [<span style="color:#eedd82;">Hd</span>|<span style="color:#eedd82;">Tail</span>]) -&gt;
    <span style="color:#00ffff;">case</span> <span style="color:#eedd82;">Pred</span>(<span style="color:#eedd82;">Hd</span>) <span style="color:#00ffff;">of</span>
        true -&gt;<span style="color:#87cefa;"> </span>all(<span style="color:#eedd82;">Pred</span>, <span style="color:#eedd82;">Tail</span>);
        false -&gt;
            <span style="color:#ff4500;">%% </span><span style="color:#ff4500;">io:format("Hd = ~p~n", [Hd]),
</span><span style="color:#ff4500;">%%             </span><span style="color:#ff4500;">true,
</span>            false
    <span style="color:#00ffff;">end</span>;
<span style="color:#87cefa;">all</span>(<span style="color:#eedd82;">Pred</span>, []) <span style="color:#00ffff;">when</span> <span style="color:#7fffd4;">is_function</span>(<span style="color:#eedd82;">Pred</span>, 1) -&gt;<span style="color:#87cefa;"> </span>true.</pre>
<p>So the visual issue with comments is the same.</p>
<p>After reading foregoing blog post about comment-style I&#8217;ve added this line to my <em>.emacs</em>:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
(setq comment-style 'indent)</pre>
<p>Easy as pie and which means (taken from Emacs help): &#8221; &#8230;`<em>comment-start&#8217; markers should not be put at the left margin but at the current indentation of the region to comment</em>.&#8221;</p>
<p>After that addition foregoing commented block in Python mode will look like:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">binsearch</span>(seq, key, start, end):
    <span style="color:#00ffff;">if</span> end &lt; start:
        <span style="color:#00ffff;">return</span> -1
    mid = (start + end) / 2
    <span style="color:#ff4500;"># if key == seq[mid]:
</span>    <span style="color:#ff4500;">#     return mid
</span>    <span style="color:#00ffff;">if</span> key &lt; seq[mid]:
        <span style="color:#00ffff;">return</span> binsearch(seq, key, start, mid-1)
    <span style="color:#00ffff;">if</span> key &gt; seq[mid]:
        <span style="color:#00ffff;">return</span> binsearch(seq, key, start+1, end)</pre>
<p>in Erlang mode:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">all</span>(<span style="color:#eedd82;">Pred</span>, [<span style="color:#eedd82;">Hd</span>|<span style="color:#eedd82;">Tail</span>]) -&gt;
    <span style="color:#00ffff;">case</span> <span style="color:#eedd82;">Pred</span>(<span style="color:#eedd82;">Hd</span>) <span style="color:#00ffff;">of</span>
        true -&gt;<span style="color:#87cefa;"> </span>all(<span style="color:#eedd82;">Pred</span>, <span style="color:#eedd82;">Tail</span>);
        false -&gt;
            <span style="color:#ff4500;">%% </span><span style="color:#ff4500;">io:format("Hd = ~p~n", [Hd]),
</span>            <span style="color:#ff4500;">%% </span><span style="color:#ff4500;">true,
</span>            false
    <span style="color:#00ffff;">end</span>;
<span style="color:#87cefa;">all</span>(<span style="color:#eedd82;">Pred</span>, []) <span style="color:#00ffff;">when</span> <span style="color:#7fffd4;">is_function</span>(<span style="color:#eedd82;">Pred</span>, 1) -&gt;<span style="color:#87cefa;"> </span>true.</pre>
<p>Now I am happy. Thank you, <a href="http://edward.oconnor.cx/2007/09/comment-style">Edward</a> for the tip.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ruslanspivak.wordpress.com/13/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ruslanspivak.wordpress.com/13/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ruslanspivak.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ruslanspivak.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ruslanspivak.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ruslanspivak.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ruslanspivak.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ruslanspivak.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ruslanspivak.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ruslanspivak.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ruslanspivak.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ruslanspivak.wordpress.com/13/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=13&subd=ruslanspivak&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/09/20/comment-dwim-and-comment-style/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4d73d92d1e35b86c5c45667b7a036da3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">alienoid</media:title>
		</media:content>
	</item>
		<item>
		<title>Erlang for Python programmers: Part II</title>
		<link>http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/</link>
		<comments>http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/#comments</comments>
		<pubDate>Sun, 16 Sep 2007 21:54:23 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/</guid>
		<description><![CDATA[In this short tutorial we will take a look at comparison operations, some arithmetic operations and modules. You may also want to skim over Inro and Part I. Comparison operations Python Erlang Description Erlang Example --------+--------+-----------------------+---------------- &#60; &#60; strictly less than --------+--------+-----------------------+---------------- &#60;= =&#60; less than or equal --------+--------+-----------------------+---------------- &#62; &#62; strictly greater than --------+--------+-----------------------+---------------- [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=11&subd=ruslanspivak&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>In this short tutorial we will take a look at comparison operations, some arithmetic operations and modules. You may also want to skim over <a href="http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/">Inro</a> and <a href="http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/">Part I</a>.</p>
<h3><u><strong>Comparison operations</strong></u></h3>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
 Python   Erlang   Description             Erlang Example
 --------+--------+-----------------------+----------------
  &lt;        &lt;        strictly less than
 --------+--------+-----------------------+----------------
  &lt;=       =&lt;       less than or equal
 --------+--------+-----------------------+----------------
  &gt;        &gt;        strictly greater than
 --------+--------+-----------------------+----------------
  &gt;=       &gt;=       greater than or equal
 --------+--------+-----------------------+----------------
  !=       /=       not equal
 --------+--------+-----------------------+----------------
  ==       ==       equal                   1&gt; 1 == 1.
                                            true
                                            2&gt; 1 == 1.0.
                                            true
 --------+--------+-----------------------+----------------
           =:=      exactly equal to        1&gt; 1 =:= 1.
                                            true
                                            2&gt; 1 =:= 1.0.
                                            false
 --------+--------+-----------------------+----------------
           =/=      exactly not equal to
 --------+--------+-----------------------+----------------
  is                object identity
 --------+--------+-----------------------+----------------
  is not            negated obj identity</pre>
<h4><u>Python notes</u></h4>
<p>Above comparison operations are supported by all objects. In Python you can chain comparisons:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x, y, z = 1, 3, 7</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x &lt; y &lt;= z</span>
True
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x &lt; y and y &lt;= z</span>
True</pre>
<p>Foregoing examples are identical, except that in second case <em><strong>y</strong></em> is evaluated twice.</p>
<h4><u>Erlang notes</u></h4>
<p>Following order is defined:</p>
<p><em>number &lt; atom &lt; reference &lt; fun &lt; port &lt; pid &lt; tuple &lt; list &lt; binary</em></p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">5 &lt; erlang.</span>
true
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">erlang &lt; make_ref().</span>
true</pre>
<p>Both Erlang comparison operators (<strong>&lt;, =&lt;, &gt;, &gt;=, /=, ==</strong>) and Python comparison operators(<strong>&lt;, &lt;=, &gt;, &gt;=, !=, ==</strong>) make type coerce, &#8220;narrower&#8221; type is widened to that of another, ie when comparing integer and float first integer is converted to float, etc.<br />
Erlang has special operators without type coerce though: <strong>=:= </strong>and <strong>=/=</strong></p>
<h3><strong><u>Arithmetic operations</u></strong></h3>
<p>I&#8217;ll provide only several operations, for more take a look at corresponding language references.</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
 Python   Python Desc.         Erlang    Erlang Desc.   Example
 --------+--------------------+---------+--------------+--------------------
  x % y    remainder            X rem Y   integer        &gt;&gt;&gt; 7 % 3
           of x / y                       remainder      1
                                          of X / Y       &gt;&gt;&gt; 7.0 % 3
                                                         1.0

                                                         1&gt; 7 rem 3.
                                                         1
                                                         1&gt; 7.0 rem 3.
                                                         =ERROR REP..
 --------+--------------------+---------+--------------+--------------------
  x / y    quotient             X / Y     floating       &gt;&gt;&gt; 7 / 3
           of x and y                     point          2
                                          division       &gt;&gt;&gt; 7.0 / 3
                                                         2.3333333333333335

                                                         1&gt; 7 / 3.
                                                         2.33333
 --------+--------------------+---------+--------------+--------------------
  x // y   (floored) quotient   X div Y   integer        &gt;&gt;&gt; 7 // 3
           of x and y,                    division       2
           integer division                              &gt;&gt;&gt; 7.5 // 3
           (result type is                               2.0
           not forced to be
           int)                                          1&gt; 7 div 3.
                                                         2</pre>
<h3><u><strong>Modules</strong></u></h3>
<p>Code in Erlang is organized into units called modules, which is familiar word for Python programmer.</p>
<p>Let&#8217;s define sample module with function declaration stored in file <em><strong>mymath.erl</strong></em> :</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([fact/1]).

<span style="color:#87cefa;">fact</span>(0) -&gt;<span style="color:#87cefa;"> </span>1;
<span style="color:#87cefa;">fact</span>(<span style="color:#eedd82;">N</span>) -&gt;<span style="color:#87cefa;"> </span><span style="color:#eedd82;">N</span> * fact(<span style="color:#eedd82;">N</span>-1).</pre>
<p><u>What we see here:</u></p>
<ol>
<li> module&#8217;s source code is stored in file with <strong>.erl</strong> extension</li>
<li>module consists of <strong>attributes</strong> and <strong>function declarations</strong> which are terminated by <strong>period</strong> (<strong>.</strong>)</li>
<li>we should provide module declaration defining name of the module</li>
</ol>
<ul>
<li>module name should be atom</li>
<li>module name is the same as file name minus <strong>.erl</strong> extension</li>
<li>module declaration is mandatory</li>
<li>module declaration attribute should be defined first.</li>
</ul>
<p>To make functions defined in module accessible outside the module we need to export them, for this <strong>-export</strong> module attribute exists. We write exported functions inside square brackets in form of <strong>func/N</strong> where <strong>N</strong> is the number of arguments of function, called <strong>arity.</strong> I&#8217;ll repeat that functions not pointed in <strong>-export</strong> will not be accessible outside module.</p>
<p>Before code can be run, module must be compiled. Resulting compiled file will contain extension <strong>.beam</strong></p>
<p>If you use Emacs you can compile module with <strong>C-c C-k</strong> and see results in erlang shell:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">c("/home/alienoid/dev/erlang/mymath", [{outdir, "/home/alienoid/dev/erlang/"}]).</span>
{ok,mymath}</pre>
<p>Or you can compile it directly in shell. Make sure your shell&#8217;s current directory is where your <strong>mymath.erl</strong> lives, if it&#8217;s not the case use <em><strong>cd</strong></em> command in erlang shell, <em>cd(&#8220;/path/to/dir/with/mymath.erl&#8221;)</em> :</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">c(mymath).</span>
{ok,mymath}</pre>
<p>To invoke our function <strong>fact</strong> we use syntax <strong>mod:func</strong> :</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">mymath:fact(4).</span>
24</pre>
<p>Erlang has also <strong>-import</strong> attribute which allows to import functions into modules, so that you don&#8217;t need to use fully-qualified name <strong>mod:func</strong> to invoke function, again familiar behaviour and naming to Python programmer.</p>
<p>Erlang allows to insert code from file as-is with <strong>-include</strong> attribute at point where <strong>-import </strong>is defined, this is used to include records and macro definitions, for example.</p>
<p>Comments in Erlang module begin with character &#8220;<strong>%</strong>&#8220;, continue up to end-of-line and may be placed anywhere except inside string and quoted atoms.<br />
Like in Python Erlang has no multiline comments.<br />
If you use Emacs you can easily comment whole region with <strong>M-;</strong> command after you marked it.</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-module</span>(mymath).
<span style="color:#87cefa;">-export</span>([fact/1, print_double/1]).
<span style="color:#87cefa;">-import</span>(lists, [foreach/2]).
<span style="color:#87cefa;">-include</span>(<span style="color:#ffa07a;">"my_records.hrl"</span>).

<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">sum(L) -&gt;
</span><span style="color:#ff4500;">%%     </span><span style="color:#ff4500;">sum(L, 0).
</span>
<span style="color:#ff4500;">%% </span><span style="color:#ff4500;">sum([H|T], Acc) -&gt;
</span><span style="color:#ff4500;">%%     </span><span style="color:#ff4500;">sum(T, H+Acc);
</span><span style="color:#ff4500;">%% </span><span style="color:#ff4500;">sum([], Acc) -&gt; Acc.
</span>
<span style="color:#87cefa;">fact</span>(0) -&gt;<span style="color:#87cefa;"> </span>1;
<span style="color:#87cefa;">fact</span>(<span style="color:#eedd82;">N</span>) -&gt;<span style="color:#87cefa;"> </span><span style="color:#eedd82;">N</span> * fact(<span style="color:#eedd82;">N</span>-1).
<span style="color:#87cefa;">print_double</span>(<span style="color:#eedd82;">L</span>) -&gt;
    foreach(<span style="color:#00ffff;">fun</span>(<span style="color:#eedd82;">X</span>) -&gt;<span style="color:#87cefa;"> </span>io:format(<span style="color:#ffa07a;">"Double of ~p = ~p~n"</span>, [<span style="color:#eedd82;">X</span>, <span style="color:#eedd82;">X</span>*2]) <span style="color:#00ffff;">end</span>, <span style="color:#eedd82;">L</span>).</pre>
<p>Fin.</p>
<p>Next tutorial will be devoted to thorough exploration of functions in Erlang.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ruslanspivak.wordpress.com/11/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ruslanspivak.wordpress.com/11/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ruslanspivak.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ruslanspivak.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ruslanspivak.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ruslanspivak.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ruslanspivak.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ruslanspivak.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ruslanspivak.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ruslanspivak.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ruslanspivak.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ruslanspivak.wordpress.com/11/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=11&subd=ruslanspivak&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4d73d92d1e35b86c5c45667b7a036da3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">alienoid</media:title>
		</media:content>
	</item>
		<item>
		<title>How to say big numbers in English: Common Lisp</title>
		<link>http://ruslanspivak.com/2007/09/12/how-to-say-big-numbers-in-english-common-lisp/</link>
		<comments>http://ruslanspivak.com/2007/09/12/how-to-say-big-numbers-in-english-common-lisp/#comments</comments>
		<pubDate>Wed, 12 Sep 2007 09:08:46 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[common lisp]]></category>
		<category><![CDATA[emacs]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/09/12/how-to-say-big-numbers-in-english-common-lisp/</guid>
		<description><![CDATA[When i was describing notations and representation of numbers in Erlang(and Python) i forgot to mention very cool feature of format function in Common Lisp, with which i got acquainted exploring highly-recommended Practical Common Lisp book. This feature is ~R directive which knows how to say really big numbers in English words. Here is the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=10&subd=ruslanspivak&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>When i was describing <a href="http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/">notations and representation of numbers in Erlang(and Python)</a> i forgot to mention very cool feature of <strong>format </strong>function in Common Lisp, with which i got acquainted exploring highly-recommended <a href="http://www.gigamonkeys.com/book/">Practical Common Lisp</a> book.</p>
<p>This feature is  <strong>~R</strong> directive which knows how to say really big numbers in English words.</p>
<p>Here is the example (I use <a href="http://sbcl.sourceforge.net/">SBCL</a> + <a href="http://common-lisp.net/project/slime/">SLIME</a>):</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">CL-USER&gt; </span>(format nil "~R" 1604872898756737459538)
<span style="color:#ff0000;">"one sextillion six hundred four quintillion eight hundred seventy-two
quadrillion eight hundred ninety-eight trillion seven hundred fifty-six
billion seven hundred thirty-seven million four hundred fifty-nine
thousand five hundred thirty-eight"</span></pre>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ruslanspivak.wordpress.com/10/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ruslanspivak.wordpress.com/10/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ruslanspivak.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ruslanspivak.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ruslanspivak.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ruslanspivak.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ruslanspivak.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ruslanspivak.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ruslanspivak.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ruslanspivak.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ruslanspivak.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ruslanspivak.wordpress.com/10/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=10&subd=ruslanspivak&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/09/12/how-to-say-big-numbers-in-english-common-lisp/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4d73d92d1e35b86c5c45667b7a036da3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">alienoid</media:title>
		</media:content>
	</item>
		<item>
		<title>Erlang for Python programmers: Part I</title>
		<link>http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/</link>
		<comments>http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/#comments</comments>
		<pubDate>Sun, 09 Sep 2007 15:06:50 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/</guid>
		<description><![CDATA[Let&#8217;s skim over data types in Erlang today. Check previous tutorial for introduction. Numbers In Erlang there are two types of numeric literals: integers and floats. In Python there are four of them: plain integers(usually called just integers), long integers, floating point numbers, and imaginary numbers. In addition to conventional notation Erlang has its own [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=9&subd=ruslanspivak&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s skim over data types in Erlang today. Check <a href="http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/">previous tutorial</a> for introduction.</p>
<h3><u><strong>Numbers</strong></u></h3>
<p>In Erlang there are two types of numeric literals: <strong>integers</strong> and <strong>floats</strong>.<br />
In Python there are four of them: <strong>plain integers</strong>(usually called just integers), <strong>long integers</strong>, <strong>floating point numbers</strong>, and <strong>imaginary numbers</strong>.</p>
<p>In addition to conventional notation Erlang has its own specific notations:<br />
1)  <strong>$char</strong><br />
Gives ASCII value of char<br />
2)  <strong>base#value</strong><br />
Produces integer. Base is in range [2,36]</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">$A.</span>
65
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">2#111.</span>
7
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">16#1A.</span>
26
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">5.</span>
5
<span style="color:#00ffff;">5&gt; </span><span style="font-weight:bold;">2.55.</span>
2.55000</pre>
<p>In Python we can define <em>octinteger </em>and <em>hexinteger</em> correspondingly with:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">017, 0x1A</span>
<span style="background-color:#40e0d0;">(</span>15, 26<span style="background-color:#40e0d0;">)</span></pre>
<p>To produce integer from different bases in Python we may use built-in<strong> int</strong>([x[, <em>radix</em>]]), where <em>radix</em> is in range [2,36]:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">int("111", 2), int("1A", 16)</span>
<span style="background-color:#40e0d0;">(</span>7, 26<span style="background-color:#40e0d0;">)</span></pre>
<h3><u><strong>Atom</strong></u></h3>
<p>An atom is a literal or a constant with name. Atoms should start with<em> small letter</em> or it should be enclosed in single quote(&#8216;) if it contains other characters than alphanumeric characters, _, or @.<br />
Atoms can not have values like variables, they are simply names (constant with name).</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">erlang.</span>
erlang
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">'hello world'.</span>
'hello world'
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">'Erlang'.</span>
'Erlang'</pre>
<p>In Python there are also atoms in form of identifiers or literals, but no correspondence with Erlang&#8217;s <em>constant with name</em> type of atom.</p>
<p>More examples with atoms to come when we get acquainted with other data types<br />
and parts of Erlang.</p>
<h3><u><strong>Binary</strong></u></h3>
<p>From a reference manual:<br />
<em> &#8220;A binary is used to store an area of untyped memory.<br />
Binaries are expressed using the bit syntax.&#8221;</em></p>
<p>This data type allows to store large raw chunks of memory in an efficient way, much more space-efficient than in lists or tuples.</p>
<p>Binaries are written in double less-than and greater-than brackets and printed in that form as well.<br />
They can be constructed from set of constants or string literal:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">&lt;&lt;1,2,3&gt;&gt;.</span>
&lt;&lt;1,2,3&gt;&gt;
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">&lt;&lt;"erlang"&gt;&gt;.</span>
&lt;&lt;"erlang"&gt;&gt;</pre>
<p>Or from bound variables:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">A = 1, B = 2, C = 3.</span>
3
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">Bin = &lt;&lt;A, B, C&gt;&gt;.</span>
&lt;&lt;1,2,3&gt;&gt;</pre>
<p>Remember <a href="http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/">pattern matching </a>?<br />
Binary (<strong>Bin</strong> for short) can also be used for matching:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">5&gt; </span><span style="font-weight:bold;">&lt;&lt;X, Y, Z&gt;&gt; = Bin.</span>
&lt;&lt;1,2,3&gt;&gt;
<span style="color:#00ffff;">6&gt; </span><span style="font-weight:bold;">X.</span>
1
<span style="color:#00ffff;">7&gt; </span><span style="font-weight:bold;">Y.</span>
2
<span style="color:#00ffff;">8&gt; </span><span style="font-weight:bold;">Z.</span>
3</pre>
<p>There is more than that, namely <strong>bit syntax</strong> which allows to pack/unpack sequences of bits in Bin. Actually bit syntax is an extension to pattern matching.<br />
Let&#8217;s pack three variables into 16 bit memory area in a variable <em>Mem</em>, then unpack it to another three variables using bit syntax:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">X = 2.</span>
2
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">Y = 40.</span>
40
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">Z = 30.</span>
30
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">Mem = &lt;&lt;X:3, Y:7, Z:6&gt;&gt;.</span>
&lt;&lt;74,30&gt;&gt;
<span style="color:#00ffff;">5&gt; </span><span style="font-weight:bold;">&lt;&lt;X1:3, Y1:7, Z1:6&gt;&gt; = Mem.</span>
&lt;&lt;74,30&gt;&gt;
<span style="color:#00ffff;">6&gt; </span><span style="font-weight:bold;">X1.</span>
2
<span style="color:#00ffff;">7&gt; </span><span style="font-weight:bold;">Y1.</span>
40
<span style="color:#00ffff;">8&gt; </span><span style="font-weight:bold;">Z1.</span>
30</pre>
<p>In foregoing output you see that after packing shell prints packed three variables as &lt;&lt;74,30&gt;&gt; which is 16 bits.</p>
<p>In Python 2.5 there is no built-in data type to support binary data, but in Python 3000 binary data is represented by a separate mutable <em>&#8220;bytes&#8221;</em> data type.</p>
<h3><u><strong>Fun</strong></u></h3>
<p>Fun is an <em>anonymous</em> function, ie without name.</p>
<p>In Python this is infamous <strong>lambda</strong>, which had many debates whether it should remain in language or not. Personally i like <strong>lambda</strong> and glad it survived and will continue its life in Python 3000.</p>
<p>But Ok, back to Erlang&#8217;s <strong>Fun</strong>. Here how we can define it in shell:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">Double = fun(X) -&gt; X * 2 end.</span>
#Fun&lt;erl_eval.6.56006484&gt;
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">Double(4).</span>
8</pre>
<p>In contrast to Python Erlang&#8217;s Fun can contain statements and is <em>&#8220;more advanced&#8221;</em> in general:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">Print_val = fun(X) -&gt; io:format("X = ~p~n", [X]), X*2 end.</span>
#Fun&lt;erl_eval.6.56006484&gt;
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">Print_val(3).</span>
X = 3
6</pre>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">print_val = lambda x: print 'x = %d' % x; x*2</span>
  File "&lt;stdin&gt;", line 1
    print_val = lambda x: print 'x = %d' % x; x*2
                              ^
<span style="color:#87cefa;">SyntaxError</span>: invalid syntax
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">print_val = lambda x: x*2</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">print_val(3)</span>
6</pre>
<p>More advanced examples of Fun like Funs with several different clauses i&#8217;ll show when discussing in details functions in Erlang in upcoming tutorials.</p>
<h3><u><strong>Tuple</strong></u></h3>
<p>It&#8217;s a compound data type with fixed number of terms (Term is a piece of data of any data type). Number of elements in tuple is called <strong>size</strong> of tuple.<br />
Syntax of tuples is:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">Tuple = {ruslan, 28}.</span>
{ruslan,28}
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">Info = {data, Tuple}.</span>
<span style="background-color:#40e0d0;">{</span>data,{ruslan,28}<span style="background-color:#40e0d0;">}</span></pre>
<p>In Python tuples are defined with or without enclosing parentheses:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">tup = "ruslan", 28</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">tup</span>
('ruslan', 28)
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">info = ('data', tup)</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">info</span>
<span style="background-color:#40e0d0;">(</span>'data', ('ruslan', 28)<span style="background-color:#40e0d0;">)</span></pre>
<p>To get number of elements in tuple.</p>
<p>Erlang:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">size(Info).</span>
2</pre>
<p>Python:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">len(info)</span>
2</pre>
<h3><u><strong>List</strong></u></h3>
<p>List is a compound data type with variable number of terms. Number of elements in a list is called <strong>length</strong> of the list.</p>
<p>List is declared in square brackets like in Python.</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">List = [1, 2, 3, "erlang"].</span>
<span style="background-color:#40e0d0;">[</span>1,2,3,"erlang"<span style="background-color:#40e0d0;">]</span></pre>
<p>Now Erlang specific part, which may be familiar to you if you know a bit Lisp and its CAR/CDR stuff:<br />
List is either an empty list [] or may be represented as head (first element &#8211; CAR in Lisp) and tail (remainder of list &#8211; CDR in Lisp) which is also a list and often you can see it in form like <strong>[H|T]</strong>.<br />
This representation is recursive:<br />
[]<br />
[c | []]<br />
[b | [c | []]]<br />
[a | [b | [c | []]]]<br />
are all lists actually.</p>
<p>Let&#8217;s define list in shell:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">List = [a, 1, {b, 2}].</span>
<span style="background-color:#40e0d0;">[</span>a,1,{b,2}<span style="background-color:#40e0d0;">]</span></pre>
<p>and unpack it with pattern matching to head and tail:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">[H|T] = List.</span>
[a,1,{b,2}]
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">H.</span>
a
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">T.</span>
<span style="background-color:#40e0d0;">[</span>1,{b,2}<span style="background-color:#40e0d0;">]</span></pre>
<p>As you see <em>T(tail)</em> above is also a list.</p>
<p>We can also construct list using head and tail syntax:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">5&gt; </span><span style="font-weight:bold;">List2 = [c|T].</span>
[c,1,{b,2}]</pre>
<p>Working with Erlang you&#8217;ll see/use this syntax quite often.</p>
<p>To get number of elements in list.</p>
<p>Erlang:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">6&gt; </span><span style="font-weight:bold;">length(List2).</span>
3</pre>
<p>Python:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">len([1, 2, 3, "python"])</span>
4</pre>
<h3><u><strong>String</strong></u></h3>
<p>In Python string type is immutable sequence of characters. In Python there is no separate character type, a character is represented by a string of one item. String literals are written in single or double quotes:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">'xyz', "xyz"</span>
<span style="background-color:#40e0d0;">(</span>'xyz', 'xyz'<span style="background-color:#40e0d0;">)</span></pre>
<p>In Erlang strings are enclosed in double quotes, but unlike Python string is not separate data type actually. String &#8220;erlang&#8221; is just shorthand for list [$e, $r, $l, $a, $n, $g].</p>
<p>Adjacent string literals are concatenated at compile time:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">"hello" ", world" " in " "erlang".</span>
"hello, world in erlang"</pre>
<p>In Python behaviour with adjacent strings is the same:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">'hello' ', world' ' in ' 'python'</span>
'hello, world in python'</pre>
<h3><u><strong>Boolean</strong></u></h3>
<p>Again unlike Python Erlang has no built-in <strong>Boolean</strong> type, but it uses atoms <strong>true</strong> and <strong>false</strong> to denote <em>Boolean</em> values:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">1 &lt; 2.</span>
true
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">true or false.</span>
true</pre>
<p>In Python Boolean is separate data type:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">type(True), type(False)</span>
(&lt;type 'bool'&gt;, &lt;type 'bool'&gt;)
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">1 &lt; 2</span>
True
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">True or False</span>
True</pre>
<h3><strong><u>Record</u></strong></h3>
<p>Record is a data structure to hold fixed number of elements and it provides method to associate a name with particular element in tuple. It resembles <em>structure</em> in <em>C</em>. Record is not true data type, it is <em>&#8220;tuple in disguise&#8221;</em>(TM).<br />
It&#8217;s syntax is:<br />
<strong> -record(Name, {key1=Default1, key2, &#8230;}).</strong></p>
<p>But in shell we can not use <strong>-record</strong> syntax and we do not yet know about modules where it can be defined, so we&#8217;ll use <strong>&#8216;rd&#8217;</strong> shell command to define record:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">rd(info, {name="ruslan", age=28, height, weight}).</span>
info</pre>
<p>Now let&#8217;s create instance of record:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">X = #info{}.</span>
#info{name = "ruslan",age = 28,height = undefined,weight = undefined}
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">X.</span>
#info<span style="background-color:#40e0d0;">{</span>name = "ruslan",age = 28,height = undefined,weight = undefined<span style="background-color:#40e0d0;">}</span></pre>
<p>As you see <em>height</em> and <em>weight</em> got <em>&#8220;undefined&#8221;</em> value.</p>
<p>To extract fields of record we use pattern matching:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">#info{name=Name, age=Age} = X.</span>
#info{name = "ruslan",age = 28,height = undefined,weight = undefined}
<span style="color:#00ffff;">5&gt; </span><span style="font-weight:bold;">Name.</span>
"ruslan"
<span style="color:#00ffff;">6&gt; </span><span style="font-weight:bold;">Age.</span>
28</pre>
<p>We can also access field of record with <strong>&#8220;dot syntax&#8221;</strong>:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">7&gt; </span><span style="font-weight:bold;">X#info.name.</span>
"ruslan"</pre>
<p>Erlang has more data types like <strong>Pid</strong>, <strong>Port identifier</strong>, <strong>Reference</strong> which will be described later in more advanced topics.There is no direct correspondence to Python&#8217;s built-in data types like <em>dictionaries</em> and <em>sets</em>, but Erlang has modules which provide the same semantics.</p>
<p>That&#8217;s it for today.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ruslanspivak.wordpress.com/9/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ruslanspivak.wordpress.com/9/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ruslanspivak.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ruslanspivak.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ruslanspivak.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ruslanspivak.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ruslanspivak.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ruslanspivak.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ruslanspivak.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ruslanspivak.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ruslanspivak.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ruslanspivak.wordpress.com/9/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=9&subd=ruslanspivak&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/09/09/erlang-for-python-programmers-part-i/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4d73d92d1e35b86c5c45667b7a036da3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">alienoid</media:title>
		</media:content>
	</item>
		<item>
		<title>Erlang for Python programmers: Intro</title>
		<link>http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/</link>
		<comments>http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/#comments</comments>
		<pubDate>Sun, 26 Aug 2007 22:51:32 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/</guid>
		<description><![CDATA[I assume you have already installed Erlang on your system and are able to run erlang shell either from command line or from within Emacs (C-c C-z). This is a view of Eshell from my Emacs: Erlang (BEAM) emulator version 5.5.2 [async-threads:0] [hipe] [kernel-poll:false] Eshell V5.5.2 (abort with ^G) 1&#62; Let&#8217;s do a simple thing [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=8&subd=ruslanspivak&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>I assume you have already installed <a href="http://www.erlang.org/doc/installation_guide/part_frame.html">Erlang</a> on your system and are able to run erlang shell either from command line or from within <a href="http://www.erlang.org/doc/apps/tools/erlang_mode_chapter.html">Emacs</a> (<em>C-c C-z</em>).</p>
<p>This is a view of Eshell from my Emacs:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
Erlang (BEAM) emulator version 5.5.2  [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.5.2  (abort with ^G)
<span style="color:#00ffff;">1&gt; </span></pre>
<p>Let&#8217;s do a simple thing and try to assign a value to a variable in the Eshell. First you should know that variables in Erlang start with uppercase letter or underscore (_), for example:</p>
<ul>
<li>X</li>
<li>Name</li>
<li>Address</li>
<li>_</li>
<li>_NoWarn</li>
</ul>
<p>Ok, let&#8217;s finally assign some value to a variable X:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">X = 4.</span>
4
<span style="color:#00ffff;">2&gt;</span></pre>
<p>So far, so good. Make sure to type final &#8220;.&#8221; at the end of expression when you are done entering code.</p>
<p>Let&#8217;s assign new value to X:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">X = 5.</span>

=ERROR REPORT==== 27-Aug-2007::00:23:02 ===
Error in process &lt;0.29.0&gt; with exit value: {{badmatch,5},[{erl_eval,expr,3}]}

** exited: {{badmatch,5},[{erl_eval,expr,3}]} **
<span style="color:#00ffff;">3&gt; </span></pre>
<p>Here you need to understand and remember couple of things:</p>
<ol>
<li>Erlang uses <strong>single assignment</strong>, a variable can only be bound once, bar none.</li>
<li>In  expression <strong>X =  5</strong> operator <strong>= </strong>is not an assignment, but <strong>match operator </strong>and variables are bound to values using <strong>pattern matching </strong>mechanism.</li>
</ol>
<p>I think it won&#8217;t be an exaggeration if I say that <em>Pattern Matching</em> permeates Erlang. To understand why we got ERROR REPORT in above example with <strong>{badmatch, 5}</strong> let&#8217;s dive into this pattern matching a bit.</p>
<p>When you use pattern matching&#8217;s = operator left side called <strong>pattern</strong> is matched against right side which is a <strong>term</strong>(piece of data of any Erlang&#8217;s data type: integer, float, list, tuple, etc). If your matching fails you get run-time error, if it succeeds then any unbound variable in lefthand pattern becomes bound.</p>
<p>Returning to our example &#8211; first we had an unbound variable:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">1&gt; </span><span style="font-weight:bold;">X.</span>
** 1: variable 'X' is unbound **
<span style="color:#00ffff;">2&gt; </span></pre>
<p>Then we bound value to variable X with pattern matching:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">2&gt; </span><span style="font-weight:bold;">X = 4.</span>
4
<span style="color:#00ffff;">3&gt; </span><span style="font-weight:bold;">X.</span>
4
<span style="color:#00ffff;">4&gt; </span></pre>
<p>Now as the variable X is bound we can&#8217;t change its value any more (remember <strong>single assignment</strong>?) otherwise we&#8217;ll get <strong>badmatch</strong> error like in foregoing X = 5 (4 does not match 5), but we may use = to <strong>match </strong>our variable:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">4&gt; </span><span style="font-weight:bold;">X = 4.</span>
4
<span style="color:#00ffff;">5&gt; </span></pre>
<p>Let&#8217;s add a bit of tuples to pattern matching. In Erlang tuple is defined inside {&#8230;}. ie:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">5&gt; </span><span style="font-weight:bold;">{2, 3}.</span>
{2,3}
<span style="color:#00ffff;">6&gt; </span></pre>
<p>and now pattern matching:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">6&gt; </span><span style="font-weight:bold;">{X, Y} = {2, 3}.</span>

=ERROR REPORT==== 27-Aug-2007::01:10:45 ===
Error in process &lt;0.29.0&gt; with exit value: {{badmatch,{2,3}},[{erl_eval,expr,3}]}

** exited: {{badmatch,{2,3}},[{erl_eval,expr,3}]} **
<span style="color:#00ffff;">7&gt; </span><span style="font-weight:bold;">{X, Y} = {4, 3}.</span>
{4,3}
<span style="color:#00ffff;">8&gt; </span><span style="font-weight:bold;">X.</span>
4
<span style="color:#00ffff;">9&gt; </span><span style="font-weight:bold;">Y.</span>
3
<span style="color:#00ffff;">10&gt; </span></pre>
<p>In first attempt we tried to match X with 2 and the matching failed as the value of X is 4, in a second attempt the matching succeeded and unbound variable Y also got its value (became bound).</p>
<p>This may look to you like <strong>tuple unpacking</strong> in Python:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x, y = (4, 3)</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x, y</span>
(4, 3)
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x, y = (5, 3)</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">x, y</span>
<span style="background-color:#40e0d0;">(</span>5, 3<span style="background-color:#40e0d0;">)</span></pre>
<p>but it&#8217;s only visual similarity, though i must admit, useful one.</p>
<p>That&#8217;s it for today, later you&#8217;ll see how pattern matching is uber-useful and how it is used in different parts of Erlang&#8217;s constructs.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ruslanspivak.wordpress.com/8/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ruslanspivak.wordpress.com/8/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ruslanspivak.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ruslanspivak.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ruslanspivak.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ruslanspivak.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ruslanspivak.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ruslanspivak.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ruslanspivak.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ruslanspivak.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ruslanspivak.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ruslanspivak.wordpress.com/8/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=8&subd=ruslanspivak&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/08/27/erlang-for-python-programmers-intro/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4d73d92d1e35b86c5c45667b7a036da3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">alienoid</media:title>
		</media:content>
	</item>
		<item>
		<title>Erlang man pages in Emacs</title>
		<link>http://ruslanspivak.com/2007/08/19/erlang-man-pages-in-emacs/</link>
		<comments>http://ruslanspivak.com/2007/08/19/erlang-man-pages-in-emacs/#comments</comments>
		<pubDate>Sun, 19 Aug 2007 11:56:47 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
				<category><![CDATA[emacs]]></category>
		<category><![CDATA[erlang]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/08/19/erlang-man-pages-in-emacs/</guid>
		<description><![CDATA[Well it&#8217;s actually as simple as running M-x man RET module_name RET in minibuffer. I&#8217;m using Erlang setup from rpm on FC7 and by default man pages are located under /usr/lib/erlang/man/ so to use above command in minibuffer you must make sure you have your erlang&#8217;s man path either in /etc/man.config or you&#8217;ve added it [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=7&subd=ruslanspivak&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>Well it&#8217;s actually as simple as running <em>M-x man RET module_name RET</em> in minibuffer.</p>
<p>I&#8217;m using Erlang setup from rpm on FC7 and by default man pages are located under <em>/usr/lib/erlang/man/ </em>so to use above command in minibuffer you must make sure you have your erlang&#8217;s man path either in <em>/etc/man.config</em> or you&#8217;ve added it into <em>MANPATH </em>with something like<em> export MANPATH=$MANPATH:/usr/lib/erlang/man </em>in your <em>.bash_profile </em>in case your Erlang man pages are not in location accessible by default.</p>
<p>You may also pass man path in minibuffer manually without changing /etc/man.config or MANPATH. In my case to view man page for <em>&#8216;lists&#8217; </em>module it will look like:</p>
<p><em>M-x man RET -M /</em><em>usr/lib/erlang/man lists </em><em>RET</em></p>
<p>I&#8217;ve customized some stuff for myself in emacs and made binding to F6 key so that whenever i set cursor on module name in my erlang buffer and press F6 i get man page in another window poped up describing module at point. So if you have in your code or in any buffer, for example:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">(em@localhost)2&gt; </span>lists:reverse([1, 2, 3]).</pre>
<p>you need to move cursor to <strong>lists</strong> and press F6. Quite handy if you consult man pages often, which is the case for me now as i learn Erlang.</p>
<p>Here is the corresponding elisp helper function and key binding from my dot emacs:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
(<span style="color:#00ffff;">defun</span> <span style="color:#87cefa;">get-erl-man</span> ()
  (interactive)
  (<span style="color:#00ffff;">let*</span> ((man-path <span style="color:#ffa07a;">"/usr/lib/erlang/man"</span>)
         (man-args (format <span style="color:#ffa07a;">"-M %s %s"</span> man-path (current-word))))
    (man man-args)))

(global-set-key [(f6)] (<span style="color:#00ffff;">lambda</span> () (interactive) (get-erl-man)))</pre>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ruslanspivak.wordpress.com/7/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ruslanspivak.wordpress.com/7/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ruslanspivak.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ruslanspivak.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ruslanspivak.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ruslanspivak.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ruslanspivak.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ruslanspivak.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ruslanspivak.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ruslanspivak.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ruslanspivak.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ruslanspivak.wordpress.com/7/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=7&subd=ruslanspivak&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/08/19/erlang-man-pages-in-emacs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4d73d92d1e35b86c5c45667b7a036da3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">alienoid</media:title>
		</media:content>
	</item>
	</channel>
</rss>