<?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:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Ruslan's Blog</title>
	<atom:link href="http://ruslanspivak.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://ruslanspivak.com</link>
	<description>Musings on dynamic languages and more than that</description>
	<pubDate>Mon, 14 Apr 2008 22:45:55 +0000</pubDate>
	<generator>http://wordpress.org/?v=MU</generator>
	<language>en</language>
			<item>
		<title>Autovivication and Y Combinator in Python</title>
		<link>http://ruslanspivak.com/2008/04/14/autovivication-and-y-combinator-in-python/</link>
		<comments>http://ruslanspivak.com/2008/04/14/autovivication-and-y-combinator-in-python/#comments</comments>
		<pubDate>Mon, 14 Apr 2008 22:45:55 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
		
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://ruslanspivak.wordpress.com/?p=29</guid>
		<description><![CDATA[Sometimes you may need to have nested dictionaries initialized without much hassle.
&#8220;Autovivication&#8221; comes in handy. What you want to achieve is:

&#62;&#62;&#62; d = dict()
&#62;&#62;&#62; d['q']['w']['r'] = 777

Of course what you&#8217;ll get will be:

&#62;&#62;&#62; d['q']['w']['r'] = 777
Traceback (most recent call last):
  File &#8220;&#60;stdin&#62;&#8221;, line 1, in &#60;module&#62;
KeyError: &#8216;q&#8217;

If you don&#8217;t need deeply nested dictionaries defaultdict [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Sometimes you may need to have nested dictionaries initialized without much hassle.</p>
<p>&#8220;Autovivication&#8221; comes in handy. What you want to achieve is:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d = dict()</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['q']['w']['r'] = 777</span>
</pre>
<p>Of course what you&#8217;ll get will be:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['q']['w']['r'] = 777</span>
Traceback (most recent call last):
  File &#8220;&lt;stdin&gt;&#8221;, line 1, in &lt;module&gt;
<span style="color:#87cefa;">KeyError</span>: &#8216;q&#8217;
</pre>
<p>If you don&#8217;t need deeply nested dictionaries <strong>defaultdict </strong> with <em>dict default factory</em> will do the job:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">from collections import defaultdict</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d = defaultdict(dict)</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d</span>
defaultdict(&lt;type &#8216;dict&#8217;&gt;, {})
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['a']['b'] = 33</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d</span>
defaultdict(&lt;type &#8216;dict&#8217;&gt;, {&#8217;a': {&#8217;b': 33}})
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['a']['b']</span>
33
</pre>
<p>Here are another ways to have unlimited level of nested dictionaries.<br />
<strong>1)</strong> Define custom class inheriting from built-in <strong>dict</strong>:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">class</span> <span style="color:#98fb98;">default_dict</span>(dict):
    <span style="color:#00ffff;">def</span> <span style="color:#87cefa;">__missing__</span>(<span style="color:#00ffff;">self</span>, key):
        <span style="color:#00ffff;">self</span>[key] = value = <span style="color:#00ffff;">self</span>.__class__()
        <span style="color:#00ffff;">return</span> value
</pre>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d = default_dict()</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d</span>
{}
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['q']['w']['r'] = 777</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d</span>
{&#8217;q': {&#8217;w': {&#8217;r': 777}}}
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['q']['w']['r']</span>
777
</pre>
<p><strong>2)</strong> Recursive function + <strong>defaultdict</strong>:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">make_dict</span>():
    <span style="color:#00ffff;">return</span> defaultdict(make_dict)
</pre>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">from collections import defaultdict</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d = defaultdict(make_dict)</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d</span>
defaultdict(&lt;function make_dict at 0xb7c5295c&gt;, {})
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['q']['w']['r'] = 777</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d</span>
defaultdict(&lt;function make_dict at 0xb7c5295c&gt;, {&#8217;q': defaultdict(&lt;function make_dict at 0xb7c5295c&gt;, {&#8217;w': defaultdict(&lt;function make_dict at 0xb7c5295c&gt;, {&#8217;r': 777})})})
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['q']['w']['r']</span>
777
</pre>
<p><strong>3)</strong> And for fun you can use <a href="http://en.wikipedia.org/wiki/Y_combinator">Y Combinator</a> (in short - making anonymous lambda recursive) which is actually as (2) but you don&#8217;t have to have recursive function defined:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">def</span> <span style="color:#87cefa;">Y</span>(g):
    <span style="color:#00ffff;">return</span> ((<span style="color:#00ffff;">lambda</span> f: f(f))
            (<span style="color:#00ffff;">lambda</span> f:
                 g(<span style="color:#00ffff;">lambda</span> x: f(f)
                   (x))))

<span style="color:#eedd82;">defdict</span> = Y(<span style="color:#00ffff;">lambda</span> mk_dict:
                <span style="color:#00ffff;">lambda</span> x=<span style="color:#00ffff;">None</span>: defaultdict(<span style="color:#00ffff;">lambda</span> x=<span style="color:#00ffff;">None</span>: mk_dict(x)))
</pre>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d = defdict()</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d</span>
defaultdict(&lt;function &lt;lambda&gt; at 0xb7c52a74&gt;, {})
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['q']['w']['r'] = 777</span>
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d</span>
defaultdict(&lt;function &lt;lambda&gt; at 0xb7c52a74&gt;, {&#8217;q': defaultdict(&lt;function &lt;lambda&gt; at 0xb7c56c6c&gt;, {&#8217;w': defaultdict(&lt;function &lt;lambda&gt; at 0xb7c56a74&gt;, {&#8217;r': 777})})})
<span style="color:#00ffff;">&gt;&gt;&gt; </span><span style="font-weight:bold;">d['q']['w']['r']</span>
777
</pre>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ruslanspivak.wordpress.com/29/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ruslanspivak.wordpress.com/29/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ruslanspivak.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ruslanspivak.wordpress.com/29/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ruslanspivak.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ruslanspivak.wordpress.com/29/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ruslanspivak.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ruslanspivak.wordpress.com/29/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ruslanspivak.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ruslanspivak.wordpress.com/29/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ruslanspivak.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ruslanspivak.wordpress.com/29/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=29&subd=ruslanspivak&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2008/04/14/autovivication-and-y-combinator-in-python/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/ruslanspivak-128.jpg" medium="image">
			<media:title type="html">alienoid</media:title>
		</media:content>
	</item>
		<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
 [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><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>
<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" /></div>]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2008/04/13/array-module-in-erlang/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/ruslanspivak-128.jpg" 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 - is an arbitrary expression
Qualifier is either a generator or a filter.
A generator is of form Pattern &#60;- [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><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> - 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(&#8221;/home/alienoid/dev/erlang/sort&#8221;, [{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 &#8220;&lt;stdin&gt;&#8221;, line 1, in &lt;module&gt;
<span style="color:#87cefa;">NameError</span>: name &#8216;x&#8217; 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>
&#8216;c&#8217;</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 &#8216;abc&#8217;)</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 &#8220;&lt;stdin&gt;&#8221;, line 1, in &lt;module&gt;
<span style="color:#87cefa;">NameError</span>: name &#8216;x&#8217; 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 &#8216;X&#8217; 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 &#8216;X&#8217; 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>
<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" /></div>]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/11/16/erlang-for-python-programmers-part-v/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/ruslanspivak-128.jpg" medium="image">
			<media:title type="html">alienoid</media:title>
		</media:content>
	</item>
		<item>
		<title>Delete blank lines with flush-lines</title>
		<link>http://ruslanspivak.com/2007/10/22/delete-blank-lines-with-flush-lines/</link>
		<comments>http://ruslanspivak.com/2007/10/22/delete-blank-lines-with-flush-lines/#comments</comments>
		<pubDate>Sun, 21 Oct 2007 23:12:07 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
		
		<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/10/22/delete-blank-lines-with-flush-lines/</guid>
		<description><![CDATA[Sometimes after I copy-paste code snippets from web page into  emacs buffer I get text with superfluous blank lines delimiting code.
Marking region and running M-x flush-lines RET ^$ RET quickly makes it better by removing those pesky blank lines. This is, of course, makes sense only if pasted code doesn&#8217;t contain blank lines you [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Sometimes after I copy-paste code snippets from web page into  emacs buffer I get text with superfluous blank lines delimiting code.</p>
<p>Marking region and running <strong>M-x flush-lines RET ^$ RET</strong> quickly makes it better by removing those pesky blank lines. This is, of course, makes sense only if pasted code doesn&#8217;t contain blank lines you want to preserve.</p>
<p><em>Update</em>:<br />
You may need to use something more complex than simple <strong>^$</strong> (something like <strong>^\W*$</strong> as regexp) if &#8220;blank&#8221; line contains some whitespace characters.</p>
<p>Example before:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-export</span>([test1/0,

         test2/0,

         test3/0,

         double/1]).</pre>
<p>After marking region and applying <strong>M-x flush-lines RET ^\W*$ RET</strong>  (in your case just <strong>^$</strong> may be sufficient):</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
<span style="color:#87cefa;">-export</span>([test1/0,
         test2/0,
         test3/0,
         double/1]).</pre>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ruslanspivak.wordpress.com/19/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ruslanspivak.wordpress.com/19/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ruslanspivak.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ruslanspivak.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ruslanspivak.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ruslanspivak.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ruslanspivak.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ruslanspivak.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ruslanspivak.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ruslanspivak.wordpress.com/19/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ruslanspivak.wordpress.com/19/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ruslanspivak.wordpress.com/19/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=19&subd=ruslanspivak&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/10/22/delete-blank-lines-with-flush-lines/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/ruslanspivak-128.jpg" medium="image">
			<media:title type="html">alienoid</media:title>
		</media:content>
	</item>
		<item>
		<title>Incremental search forward</title>
		<link>http://ruslanspivak.com/2007/10/05/incremental-search-forward/</link>
		<comments>http://ruslanspivak.com/2007/10/05/incremental-search-forward/#comments</comments>
		<pubDate>Fri, 05 Oct 2007 21:41:36 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
		
		<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/10/05/incremental-search-forward/</guid>
		<description><![CDATA[Well-known incremental search forward(isearch-forward Lisp function) which is invoked with C-s has also additional useful key-bindings which I use often to instruct what to search. After you pressed C-s in buffer they are:

C-w to yank next word or character in buffer onto the end of the search string, and search for it. You can repeatedly [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Well-known incremental search forward(<strong>isearch-forward</strong> Lisp function) which is invoked with <strong>C-s</strong> has also additional useful key-bindings which I use often to instruct what to search. After you pressed <strong>C-s</strong> in buffer they are:</p>
<ol>
<li><strong>C-w</strong> to yank next word or character in buffer onto the end of the search string, and search for it. You can repeatedly press <strong>C-w</strong> consuming next word or character.</li>
<li><strong>C-y</strong> to yank rest of line onto end of search string and search for it.</li>
<li><strong>M-n</strong>/<strong>M-p</strong> to search for the next/previous item in the search ring.</li>
</ol>
<p>As usual for more information read help (<strong>C-h k C-s</strong> or <strong>C-h f isearch-forward RET</strong> ).</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ruslanspivak.wordpress.com/18/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ruslanspivak.wordpress.com/18/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ruslanspivak.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ruslanspivak.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ruslanspivak.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ruslanspivak.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ruslanspivak.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ruslanspivak.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ruslanspivak.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ruslanspivak.wordpress.com/18/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ruslanspivak.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ruslanspivak.wordpress.com/18/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=18&subd=ruslanspivak&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/10/05/incremental-search-forward/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/ruslanspivak-128.jpg" medium="image">
			<media:title type="html">alienoid</media:title>
		</media:content>
	</item>
		<item>
		<title>align-regexp</title>
		<link>http://ruslanspivak.com/2007/10/03/align-regexp/</link>
		<comments>http://ruslanspivak.com/2007/10/03/align-regexp/#comments</comments>
		<pubDate>Wed, 03 Oct 2007 00:16:01 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
		
		<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/10/03/align-regexp/</guid>
		<description><![CDATA[This interactive Emacs Lisp function was very handy for me during some log files analysis.
You mark region, invoke function, provide regexp and voila - your region is aligned.
Example data from align-regexp help:

Fred (123) 456-7890
Alice (123) 456-7890
Mary-Anne (123) 456-7890
Joe (123) 456-7890
Let&#8217;s say we want to align region on &#8220;(&#8221; character. For that we mark region we [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This interactive Emacs Lisp function was very handy for me during some log files analysis.</p>
<p>You mark region, invoke function, provide <em>regexp </em>and voila - your region is aligned.</p>
<p>Example data from <strong>align-regexp</strong> help:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
Fred (123) 456-7890
Alice (123) 456-7890
Mary-Anne (123) 456-7890
Joe (123) 456-7890</pre>
<p>Let&#8217;s say we want to align region on &#8220;<strong>(</strong>&#8221; character. For that we mark region we want to align and invoke function with: <strong>M-x align-regexp RET (  RET</strong><br />
Result of such invocation will be:</p>
<pre style="color:#ffffff;background-color:#000000;font-size:8pt;">
Fred      (123) 456-7890
Alice     (123) 456-7890
Mary-Anne (123) 456-7890
Joe       (123) 456-7890</pre>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ruslanspivak.wordpress.com/17/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ruslanspivak.wordpress.com/17/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ruslanspivak.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ruslanspivak.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ruslanspivak.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ruslanspivak.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ruslanspivak.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ruslanspivak.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ruslanspivak.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ruslanspivak.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ruslanspivak.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ruslanspivak.wordpress.com/17/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=17&subd=ruslanspivak&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/10/03/align-regexp/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/ruslanspivak-128.jpg" 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 - 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; Double(2).
4
But Fun actually has the same [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><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 - 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(&#8221;/home/alienoid/dev/erlang/mymath&#8221;, [{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>:
&#8216;!&#8217;/2                         list_to_existing_atom/1
&#8216;$erase&#8217;/1                    list_to_float/1
&#8216;$erase&#8217;/0                    list_to_integer/2
&#8216;$get&#8217;/1                      list_to_integer/1
&#8216;$get&#8217;/0                      list_to_pid/1
&#8216;$get_keys&#8217;/1                 list_to_tuple/1
&#8216;$put&#8217;/2                      load_module/2
&#8216;*&#8217;/2                         loaded/0
&#8216;+&#8217;/1                         localtime/0
&#8216;+&#8217;/2                         localtime_to_universaltime/1
&#8216;++&#8217;/2                        localtime_to_universaltime/2
&#8230;
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,&#8230;,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;">&#8220;TIMEOUT = ~p~n&#8221;</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(&#8221;/home/alienoid/dev/erlang/mymath&#8221;, [{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> - Evaluate the following lines only if <em>Macro</em> is defined.</li>
<li><strong>else.</strong> - 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;">&#8220;{~p:~p}: ~p~n&#8221;</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;">&#8220;Debug is enabled&#8221;</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}: &#8220;Debug is enabled&#8221;
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>
<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" /></div>]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/10/02/erlang-for-python-programmers-part-iv/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/ruslanspivak-128.jpg" medium="image">
			<media:title type="html">alienoid</media:title>
		</media:content>
	</item>
		<item>
		<title>Creating tables in Emacs</title>
		<link>http://ruslanspivak.com/2007/10/01/creating-tables-in-emacs/</link>
		<comments>http://ruslanspivak.com/2007/10/01/creating-tables-in-emacs/#comments</comments>
		<pubDate>Mon, 01 Oct 2007 13:13:18 +0000</pubDate>
		<dc:creator>Ruslan Spivak</dc:creator>
		
		<category><![CDATA[emacs]]></category>

		<guid isPermaLink="false">http://ruslanspivak.com/2007/10/01/creating-tables-in-emacs/</guid>
		<description><![CDATA[Sometimes I need to create tables in Emacs as it was in post describing comparison and arithmetic operations in Python and Erlang.
Over time I became aware of several means to create tables and export them in different formats in Emacs(at the moment I&#8217;m personally interested in plain ASCII and HTML):

Excellent org-mode has built-in table editor [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Sometimes I need to create tables in Emacs as it was in <a href="http://ruslanspivak.com/2007/09/16/erlang-for-python-programmers-part-ii/">post</a> describing comparison and arithmetic operations in Python and Erlang.</p>
<p>Over time I became aware of several means to create tables and export them in different formats in Emacs(at the moment I&#8217;m personally interested in plain ASCII and HTML):</p>
<ol>
<li>Excellent <a href="http://orgmode.org/">org-mode</a> has built-in <a href="http://orgmode.org/org.html#Tables">table editor</a>  which allows easily format tables in plain ASCII</li>
<li><a href="http://table.sourceforge.net/">table.el</a> with its advanced ability to construct table layout</li>
</ol>
<p>Both modes (technically though Table mode in <em>table.el</em> is not mode) are part of modern Emacs and both allow export table in HTML format.</p>
<p>To quickly create tables personally I prefer <em>table.el</em> which provides also following features:</p>
<ol>
<li>A cell can be split horizontally and vertically.</li>
<li>A cell can span into an adjacent cell.</li>
</ol>
<p>Use <strong>C-h b </strong>in table to get self-descriptive information about table.el key bindings. In contrast to <em>org-mode</em>(or its <em>orgtbl-mode</em> minor mode) <em>table.el</em> has no special bindings to copy row/cell and yank it. But this is easily achieved by using usual region commands for rows and rectangular commands for cells.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/ruslanspivak.wordpress.com/15/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/ruslanspivak.wordpress.com/15/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ruslanspivak.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ruslanspivak.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ruslanspivak.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ruslanspivak.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ruslanspivak.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ruslanspivak.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ruslanspivak.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ruslanspivak.wordpress.com/15/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ruslanspivak.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ruslanspivak.wordpress.com/15/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ruslanspivak.com&blog=1522719&post=15&subd=ruslanspivak&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/10/01/creating-tables-in-emacs/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/ruslanspivak-128.jpg" 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=&#8216;ruslan&#8217;, type=&#8216;unknown&#8217;, **kw):
    print &#8216;key = %s, name = %s, type = [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><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;">&#8216;ruslan&#8217;</span>, type=<span style="color:#ffa07a;">&#8216;unknown&#8217;</span>, **kw):
    <span style="color:#00ffff;">print</span> <span style="color:#ffa07a;">&#8216;key = %s, name = %s, type = %s&#8217;</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;">&#8216;%s = %s&#8217;</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=&#8217;known&#8217;, 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 - <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(&#8221;/home/alienoid/dev/erlang/mymath&#8221;, [{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>
<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" /></div>]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/09/24/erlang-for-python-programmers-part-iii/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/ruslanspivak-128.jpg" 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 [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><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;">&#8220;Hd = ~p~n&#8221;</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(&#8221;Hd = ~p~n&#8221;, [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(&#8221;Hd = ~p~n&#8221;, [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>
<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" /></div>]]></content:encoded>
			<wfw:commentRss>http://ruslanspivak.com/2007/09/20/comment-dwim-and-comment-style/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/ruslanspivak-128.jpg" medium="image">
			<media:title type="html">alienoid</media:title>
		</media:content>
	</item>
	</channel>
</rss>