<?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/"
	>

<channel>
	<title>Zero Wind - Jamie Wong &#187; Tutorials</title>
	<atom:link href="http://jamie-wong.com/category/tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://jamie-wong.com</link>
	<description>Inside the mind of a Waterloo Software Engineering student</description>
	<lastBuildDate>Sun, 15 Aug 2010 05:25:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Flex/Actionscript 3: Debug Output to Console</title>
		<link>http://jamie-wong.com/2010/07/07/flexactionscript-3-debug-output-to-console/</link>
		<comments>http://jamie-wong.com/2010/07/07/flexactionscript-3-debug-output-to-console/#comments</comments>
		<pubDate>Thu, 08 Jul 2010 05:11:19 +0000</pubDate>
		<dc:creator>Jamie Wong</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[flixel]]></category>
		<category><![CDATA[trace]]></category>

		<guid isPermaLink="false">http://jamie-wong.com/?p=292</guid>
		<description><![CDATA[I recently started messing around with the Flixel framework - something built on top of Flex to make retro games. One of the first things I noticed was how difficult it is to debug things - especially complex objects. The first problem is capturing any debug output. For whatever reason, I was unable to output [...]]]></description>
			<content:encoded><![CDATA[<p>I recently started messing around with the <a href="http://flixel.org/">Flixel</a> framework - something built on top of <a href="http://www.adobe.com/products/flex/">Flex</a> to make retro games. One of the first things I noticed was how difficult it is to debug things - especially complex objects.</p>

<p>The first problem is capturing <em>any</em> debug output. For whatever reason, I was unable to output traces to anywhere useful.
My first success was with using <a href="http://demonsterdebugger.com/">De MonsterDebugger</a> to capture the output. While this was better than nothing, I needed very little of the functionality of De MonsterDebugger and it still didn't give me what I really wanted: formatted console output.</p>

<h2>print_r style output in actionscript</h2>

<p>I found a good starting point <a href="http://dev.base86.com/solo/47/actionscript_3_equivalent_of_phps_printr.html">here</a>, but the output of this wasn't exactly what I wanted. I messed around with it until I got something more familiar to me.</p>

<pre class='prettyprint'><code>package learning {
  import org.flixel.*;

  public class Debugger {
    public static function pr(obj:*, level:int = 0, output:String = ""):* {
      var objtype:String = typeof(obj);
      if (objtype == "boolean" || objtype == "string" || objtype == "number") {
        return obj;
      }

      var tabs:String = "";
      for(var i:int = 0; i &lt; level; i++) { 
        tabs += "\t"
      }

      output += "{\n";
      for(var child:* in obj) {
        output += tabs +"\t["+ child +"] =&gt; ";

        var childOutput:String = pr(obj[child], level+1);
        if(childOutput != '') output += childOutput

        output += "\n";
      }
      output += tabs + "}\n";

      return output;
    }

    public static function log(obj:*):void {
      FlxG.log(pr(obj));
      // This is a flixel thing. If you're not using flixel
      // Just use trace(pr(obj));
    }
  }
}
</code></pre>

<p>Example output</p>

<pre class='prettyprint'><code>{
    [0] =&gt; {
        [tile] =&gt; 4
        [rule] =&gt; {
            [0] =&gt; xxx
            [1] =&gt; x1x
            [2] =&gt; x1x
        }
    }
    [1] =&gt; {
        [tile] =&gt; 8
        [rule] =&gt; {
            [0] =&gt; x1x
            [1] =&gt; x1x
            [2] =&gt; xxx
        }
    }
}
</code></pre>

<p><strong>NOTE</strong>: The colored output is from <a href="http://code.google.com/p/google-code-prettify/">Prettify</a>, not the script</p>

<h2>trace output to console</h2>

<p>This, fortunately, was much less of a hassle for me to get working.</p>

<p>Reference: <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=logging_04.html">Configuring the debugger version of Flash Player</a></p>

<p><strong>Step 1</strong></p>

<p>Locate/create your <code>mm.cfg</code> file. For me this was in <code>~/mm.cfg</code>. See <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=logging_04.html">reference</a>.</p>

<p>Stick this in it: <code>TraceOutputFileEnable=1</code></p>

<p>Or, in one command: <code>echo "TraceOutputFileEnable=1" &gt; ~/mm.cfg</code></p>

<p><strong>Step 2</strong></p>

<p>Locate the location of the log file. Mine is in</p>

<p><code>~/Library/Preferences/Macromedia/Flash Player/Logs/flashlog.txt</code></p>

<p>See <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=logging_04.html">reference</a>.</p>

<p>You don't want to type this in every time you want to view the log, so add a function to your <code>.bash_profile</code></p>

<p>This is what I have:</p>

<pre class='prettyprint'><code>flashlog() { 
  tail -f $* ~/Library/Preferences/Macromedia/Flash\ Player/Logs/flashlog.txt; 
}
</code></pre>

<p><strong>Step 3</strong></p>

<p>Start debugging!</p>

<pre class='prettyprint'><code>  [learning]  flashlog -100
Warning: 'flash' has no property 'prototype'
Warning: 'flash' has no property 'prototype'
flixel v2.35 [debug]
----------------------------------------------------
{
    [0] =&gt; {
        [tile] =&gt; 4
        [rule] =&gt; {
            [0] =&gt; xxx
            [1] =&gt; x1x
            [2] =&gt; x1x
        }
    }
    [1] =&gt; {
        [tile] =&gt; 8
        [rule] =&gt; {
            [0] =&gt; x1x
            [1] =&gt; x1x
            [2] =&gt; xxx
        }
    }
}
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://jamie-wong.com/2010/07/07/flexactionscript-3-debug-output-to-console/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Lambda Functions</title>
		<link>http://jamie-wong.com/2009/12/06/lambda-functions/</link>
		<comments>http://jamie-wong.com/2009/12/06/lambda-functions/#comments</comments>
		<pubDate>Mon, 07 Dec 2009 02:49:27 +0000</pubDate>
		<dc:creator>Jamie Wong</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[filter]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[reduce]]></category>
		<category><![CDATA[sort]]></category>

		<guid isPermaLink="false">http://jamie-wong.com/?p=101</guid>
		<description><![CDATA[One day, a friend of mine called me up asking for help with his CS assignment. It was about lambda functions in scheme. Lambda functions had always been something confusing both in theory and practice for me. Why do you need them? Before I explain what they are, I'll start with a simple probably justifying [...]]]></description>
			<content:encoded><![CDATA[<p>One day, a friend of mine called me up asking for help with his CS assignment. It was about lambda functions in scheme. Lambda functions had always been something confusing both in theory and practice for me. Why do you need them? Before I explain what they are, I'll start with a simple probably justifying <i>why</i> they are.</p>

<p>All code in this post is going to be in python, but most of it can be applied to other high level languages. I've only used lambda functions in python and scheme, but I'm sure the functionality exists in many, many other languages.</p>

<h2> Sorting </h2>

<p>Sorting in python is very straight forward. If I have a list of strings in python and want to sort them, I do this:</p>


<div class="wp_codebox"><table style='width:99%;margin:0px;border:0;' ><tr id="p10116"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p101code16"><pre class="python" style="font-family:monospace;">a = <span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;banana&quot;</span>,<span style="color: #483d8b;">&quot;apple&quot;</span>,<span style="color: #483d8b;">&quot;pear&quot;</span>,<span style="color: #483d8b;">&quot;elephant&quot;</span>,<span style="color: #483d8b;">&quot;zebra&quot;</span>,<span style="color: #483d8b;">&quot;mango&quot;</span><span style="color: black;">&#93;</span>
a.<span style="color: black;">sort</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> a
<span style="color: #808080; font-style: italic;"># OUT: ['apple', 'banana', 'elephant', 'mango', 'pear', 'zebra']</span></pre></td></tr></table></div>


<p>But what happens when you try to sort a list of words containing capital letters?</p>


<div class="wp_codebox"><table style='width:99%;margin:0px;border:0;' ><tr id="p10117"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p101code17"><pre class="python" style="font-family:monospace;">a = <span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;pear&quot;</span>,<span style="color: #483d8b;">&quot;Police&quot;</span>,<span style="color: #483d8b;">&quot;apple&quot;</span>,<span style="color: #483d8b;">&quot;Airplane&quot;</span>,<span style="color: #483d8b;">&quot;banana&quot;</span>,<span style="color: #483d8b;">&quot;Bear&quot;</span><span style="color: black;">&#93;</span>
a.<span style="color: black;">sort</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> a
<span style="color: #808080; font-style: italic;"># OUT: ['Airplane', 'Bear', 'Police', 'apple', 'banana', 'pear']</span></pre></td></tr></table></div>


<p>The sorting is done purely based on the byte values of the characters. Since 'P' (ASCII 80) &lt; 'a' (ASCII 97), "Police" is placed before "apple" in the list of words. Normally when you're trying to sort a list of words, you want to do it alphabetically. So how do you fix this? You make a comparator function. Here's python's definition of the sort function.</p>

<blockquote>
    L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
    cmp(x, y) -> -1, 0, 1
</blockquote>

<p>For those of you who have used qsort in the standard C library, this isn't such an arcane concept. In python however, it is much easier (no void* madness).</p>


<div class="wp_codebox"><table style='width:99%;margin:0px;border:0;' ><tr id="p10118"><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code" id="p101code18"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> alphacmp<span style="color: black;">&#40;</span>x,y<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">cmp</span><span style="color: black;">&#40;</span>x.<span style="color: black;">lower</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>,y.<span style="color: black;">lower</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
a = <span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;pear&quot;</span>,<span style="color: #483d8b;">&quot;Police&quot;</span>,<span style="color: #483d8b;">&quot;apple&quot;</span>,<span style="color: #483d8b;">&quot;Airplane&quot;</span>,<span style="color: #483d8b;">&quot;banana&quot;</span>,<span style="color: #483d8b;">&quot;Bear&quot;</span><span style="color: black;">&#93;</span>
a.<span style="color: black;">sort</span><span style="color: black;">&#40;</span>alphacmp<span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> a
<span style="color: #808080; font-style: italic;"># OUT: ['Airplane', 'apple', 'banana', 'Bear', 'pear', 'Police']</span></pre></td></tr></table></div>


<p>Okay, great! We now have our list sorted in the intuitive way. The lower() function will ensure that the lowercase version of the strings are being compared, removing the issues of the byte comparisons. But this code seems a little longer than it could be. Normally, you wouldn't create a function for task you do only once if it was just as readable within the code body. But the sort function needs a comparator function. So how can you give sort a comparator function without having to actually declare a function? The answer is lambda functions.</p>

<h2> Lambda Functions </h2>

<p>Lambda functions are anonymous functions. What does that mean? They're functions without a declared name. Let's look at an example so you can see what I mean. In the above example, we can sort alphabetically without defining the alphacmp function like so:</p>


<div class="wp_codebox"><table style='width:99%;margin:0px;border:0;' ><tr id="p10119"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p101code19"><pre class="python" style="font-family:monospace;">a = <span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;pear&quot;</span>,<span style="color: #483d8b;">&quot;Police&quot;</span>,<span style="color: #483d8b;">&quot;apple&quot;</span>,<span style="color: #483d8b;">&quot;Airplane&quot;</span>,<span style="color: #483d8b;">&quot;banana&quot;</span>,<span style="color: #483d8b;">&quot;Bear&quot;</span><span style="color: black;">&#93;</span>
a.<span style="color: black;">sort</span><span style="color: black;">&#40;</span><span style="color: #ff7700;font-weight:bold;">lambda</span> x,y: <span style="color: #008000;">cmp</span><span style="color: black;">&#40;</span>x.<span style="color: black;">lower</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>,y.<span style="color: black;">lower</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> a
<span style="color: #808080; font-style: italic;"># OUT: ['Airplane', 'apple', 'banana', 'Bear', 'pear', 'Police']</span></pre></td></tr></table></div>


<p>So what does lambda x,y: cmp(x.lower(),y.lower()) mean? "lambda" says that the statements following define an anonymous function. "x,y:" defines the parameter list accepted by the anonymous function. "cmp(x.lower(),y.lower())" defines the return value for the lambda function. If you're still a little bit confused, read on for many many more examples. At some point, it will likely click and you'll see how valuable lambda really is.</p>

<p>Another sorting example: what if I want to sort by length of the strings instead of alphabetically? Easily done with lambda.</p>


<div class="wp_codebox"><table style='width:99%;margin:0px;border:0;' ><tr id="p10120"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p101code20"><pre class="python" style="font-family:monospace;">a = <span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;pencil&quot;</span>,<span style="color: #483d8b;">&quot;pen&quot;</span>,<span style="color: #483d8b;">&quot;cap&quot;</span>,<span style="color: #483d8b;">&quot;zebra&quot;</span>,<span style="color: #483d8b;">&quot;Blizzard&quot;</span>,<span style="color: #483d8b;">&quot;0xB4DC0DE&quot;</span>,<span style="color: #483d8b;">&quot;!&quot;</span><span style="color: black;">&#93;</span>
a.<span style="color: black;">sort</span><span style="color: black;">&#40;</span><span style="color: #ff7700;font-weight:bold;">lambda</span> x,y: <span style="color: #008000;">len</span><span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span> - <span style="color: #008000;">len</span><span style="color: black;">&#40;</span>y<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> a
<span style="color: #808080; font-style: italic;"># OUT: ['!', 'pen', 'cap', 'zebra', 'pencil', 'Blizzard', '0xB4DC0DE']</span></pre></td></tr></table></div>


<p>The use of lambda functions makes the use of many higher level functions much nicer. I'll be outlining a few of them here.</p>

<h2> map </h2>

<blockquote>
    map(function, sequence[, sequence, ...]) -> list
    
    Return a list of the results of applying the function to the items of
    the argument sequence(s).  If more than one sequence is given, the
    function is called with an argument list consisting of the corresponding
    item of each sequence, substituting None for missing values when not all
    sequences have the same length.  If the function is None, return a list of
    the items of the sequence (or a list of tuples if more than one sequence).
</blockquote>

<p>More or less, what map does is apply a function on every element of an array then return an array of the corresponding return values.</p>

<p>A very simple use for map would be making every word in a list upper case.</p>


<div class="wp_codebox"><table style='width:99%;margin:0px;border:0;' ><tr id="p10121"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p101code21"><pre class="python" style="font-family:monospace;">a = <span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;abc&quot;</span>,<span style="color: #483d8b;">&quot;cattle&quot;</span>,<span style="color: #483d8b;">&quot;not even if there's a FIRE&quot;</span>,<span style="color: #483d8b;">&quot;Jeymi!?&quot;</span><span style="color: black;">&#93;</span>
b = <span style="color: #008000;">map</span><span style="color: black;">&#40;</span><span style="color: #ff7700;font-weight:bold;">lambda</span> x: x.<span style="color: black;">upper</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>,a<span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> b
<span style="color: #808080; font-style: italic;"># OUT: ['ABC', 'CATTLE', &quot;NOT EVEN IF THERE'S A FIRE&quot;, 'JEYMI!?']</span></pre></td></tr></table></div>


<p>A more useful example involves printing out grids. Say I have a matrix of numbers, represented as a list of lists in python. The default output formatting for this in python is extremely difficult to look at.</p>


<div class="wp_codebox"><table style='width:99%;margin:0px;border:0;' ><tr id="p10122"><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code" id="p101code22"><pre class="python" style="font-family:monospace;">a = <span style="color: black;">&#91;</span>
    <span style="color: black;">&#91;</span>1,212,-13<span style="color: black;">&#93;</span>,
    <span style="color: black;">&#91;</span>41,5,614<span style="color: black;">&#93;</span>,
    <span style="color: black;">&#91;</span>7,8,91<span style="color: black;">&#93;</span>
<span style="color: black;">&#93;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> a
<span style="color: #808080; font-style: italic;"># OUT: [[1, 212, -13], [41, 5, 614], [7, 8, 91]]</span></pre></td></tr></table></div>


<p>What would be better is to output one row per line.</p>


<div class="wp_codebox"><table style='width:99%;margin:0px;border:0;' ><tr id="p10123"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code" id="p101code23"><pre class="python" style="font-family:monospace;">a = <span style="color: black;">&#91;</span>
    <span style="color: black;">&#91;</span>1,212,-13<span style="color: black;">&#93;</span>,
    <span style="color: black;">&#91;</span>41,5,614<span style="color: black;">&#93;</span>,
    <span style="color: black;">&#91;</span>7,8,91<span style="color: black;">&#93;</span>
<span style="color: black;">&#93;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: #008000;">map</span><span style="color: black;">&#40;</span><span style="color: #ff7700;font-weight:bold;">lambda</span> x: <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span>, a<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;">#OUT:</span>
<span style="color: #808080; font-style: italic;"># [1, 212, -13]</span>
<span style="color: #808080; font-style: italic;"># [41, 5, 614]</span>
<span style="color: #808080; font-style: italic;"># [7, 8, 91]</span></pre></td></tr></table></div>


<p><em>The join function concatenates a list of string, separating the elements with the separator character - in this case: "\n"</em></p>

<p>Much better! But what would be even better would be to print out the numbers in columns that line up nicely too.</p>


<div class="wp_codebox"><table style='width:99%;margin:0px;border:0;' ><tr id="p10124"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
</pre></td><td class="code" id="p101code24"><pre class="python" style="font-family:monospace;">a = <span style="color: black;">&#91;</span>
    <span style="color: black;">&#91;</span>1,212,-13<span style="color: black;">&#93;</span>,
    <span style="color: black;">&#91;</span>41,5,614<span style="color: black;">&#93;</span>,
    <span style="color: black;">&#91;</span>7,8,91<span style="color: black;">&#93;</span>
<span style="color: black;">&#93;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span>
    <span style="color: #008000;">map</span><span style="color: black;">&#40;</span>
        <span style="color: #ff7700;font-weight:bold;">lambda</span> row:
            <span style="color: #483d8b;">&quot; &quot;</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: #008000;">map</span><span style="color: black;">&#40;</span>
                <span style="color: #ff7700;font-weight:bold;">lambda</span> y: <span style="color: #483d8b;">&quot;%4d&quot;</span> <span style="color: #66cc66;">%</span> y,
                row
            <span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>,
        a
    <span style="color: black;">&#41;</span>
<span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;"># OUT:</span>
<span style="color: #808080; font-style: italic;">#   1  212  -13</span>
<span style="color: #808080; font-style: italic;">#  41    5  614</span>
<span style="color: #808080; font-style: italic;">#   7    8   91</span></pre></td></tr></table></div>


<p><em>"%4d" % y is applying the formatting string %4d to y, much the same way that printf in C and php do</em></p>

<p>Now, using a lambda function inside of a lambda function is less than readable, so I'll write out what this function does first without the maps and lambdas.</p>


<div class="wp_codebox"><table style='width:99%;margin:0px;border:0;' ><tr id="p10125"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code" id="p101code25"><pre class="python" style="font-family:monospace;">a = <span style="color: black;">&#91;</span>
    <span style="color: black;">&#91;</span>1,212,-13<span style="color: black;">&#93;</span>,
    <span style="color: black;">&#91;</span>41,5,614<span style="color: black;">&#93;</span>,
    <span style="color: black;">&#91;</span>7,8,91<span style="color: black;">&#93;</span>
<span style="color: black;">&#93;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> rowformat<span style="color: black;">&#40;</span>row<span style="color: black;">&#41;</span>:
    formatted_cells = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> element <span style="color: #ff7700;font-weight:bold;">in</span> row:
        formatted_cells.<span style="color: black;">append</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;%4d&quot;</span> <span style="color: #66cc66;">%</span> element<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">&quot; &quot;</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span>formatted_cells<span style="color: black;">&#41;</span>
&nbsp;
formatted_rows = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
<span style="color: #ff7700;font-weight:bold;">for</span> row <span style="color: #ff7700;font-weight:bold;">in</span> a:
    formatted_rows.<span style="color: black;">append</span><span style="color: black;">&#40;</span>rowformat<span style="color: black;">&#40;</span>row<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span>formatted_rows<span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;"># OUT:</span>
<span style="color: #808080; font-style: italic;">#   1  212  -13</span>
<span style="color: #808080; font-style: italic;">#  41    5  614</span>
<span style="color: #808080; font-style: italic;">#   7    8   91</span></pre></td></tr></table></div>


<p>In this case, "rowformat(row)" plays the exact same roles as "lambda row:".</p>

<h2> filter </h2>

<blockquote>
    filter(function or None, sequence) -> list, tuple, or string
    
    Return those items of sequence for which function(item) is true.  If
    function is None, return the items that are true.  If sequence is a tuple
    or string, return the same type, else return a list.
</blockquote>

<p>The filter function does just what it's name suggests: filters out items that don't meet certain requirements. Specifically, any element which does not evaluate to true when passed to the provided function will be discarded. Note that this is <em>not</em> in place - it returns the filtered list.</p>

<p>Example: remove all odd numbers from a list of numbers</p>


<div class="wp_codebox"><table style='width:99%;margin:0px;border:0;' ><tr id="p10126"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p101code26"><pre class="python" style="font-family:monospace;">a = <span style="color: black;">&#91;</span>1,2,5,0,-15,100,1400,-1337,135<span style="color: black;">&#93;</span>
a = <span style="color: #008000;">filter</span><span style="color: black;">&#40;</span><span style="color: #ff7700;font-weight:bold;">lambda</span> x: x <span style="color: #66cc66;">%</span> 2 == 0, a<span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> a
<span style="color: #808080; font-style: italic;">#OUT: [2, 0, 100, 1400]</span></pre></td></tr></table></div>


<p>Example: remove all vowels from a string</p>


<div class="wp_codebox"><table style='width:99%;margin:0px;border:0;' ><tr id="p10127"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p101code27"><pre class="python" style="font-family:monospace;">a = <span style="color: #483d8b;">&quot;Hello there! My name is Jamie, not to be confused with Jeymi.&quot;</span>
a = <span style="color: #483d8b;">&quot;&quot;</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: #008000;">filter</span><span style="color: black;">&#40;</span><span style="color: #ff7700;font-weight:bold;">lambda</span> x: <span style="color: #483d8b;">&quot;aeiou&quot;</span>.<span style="color: black;">find</span><span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span> == -1, <span style="color: #008000;">list</span><span style="color: black;">&#40;</span>a<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> a
<span style="color: #808080; font-style: italic;"># OUT: Hll thr! My nm s Jm, nt t b cnfsd wth Jym.</span></pre></td></tr></table></div>


<p>Example: build a list of all prime numbers between 0 and 100 inclusive</p>


<div class="wp_codebox"><table style='width:99%;margin:0px;border:0;' ><tr id="p10128"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code" id="p101code28"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># NOTE: This prime test is inefficient - used for readability)</span>
<span style="color: #ff7700;font-weight:bold;">def</span> isprime<span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: black;">&#40;</span>x <span style="color: #66cc66;">&lt;</span> 2<span style="color: black;">&#41;</span>: 
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">False</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span>2,x<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: black;">&#40;</span>x <span style="color: #66cc66;">%</span> i == 0<span style="color: black;">&#41;</span>:
            <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">False</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">True</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">filter</span><span style="color: black;">&#40;</span>isprime,<span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">101</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;"># OUT (placed on multiple lines for readability)</span>
<span style="color: #808080; font-style: italic;"># [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, </span>
<span style="color: #808080; font-style: italic;"># 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]</span></pre></td></tr></table></div>


<h2> reduce </h2>

<blockquote>
    reduce(function, sequence[, initial]) -> value
    
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.
</blockquote>

<p>Example: Calculate 30 factorial without using local variables</p>


<div class="wp_codebox"><table style='width:99%;margin:0px;border:0;' ><tr id="p10129"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p101code29"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># Note that range(2,n) -&gt; [2,3,...,n-1]</span>
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">reduce</span><span style="color: black;">&#40;</span><span style="color: #ff7700;font-weight:bold;">lambda</span> x,y: x<span style="color: #66cc66;">*</span>y, <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">2</span>,<span style="color: #ff4500;">31</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;"># OUT: 265252859812191058636308480000000</span></pre></td></tr></table></div>


<p>Example: Find the longest word in a list of words</p>


<div class="wp_codebox"><table style='width:99%;margin:0px;border:0;' ><tr id="p10130"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p101code30"><pre class="python" style="font-family:monospace;">a = <span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;pencil&quot;</span>,<span style="color: #483d8b;">&quot;pen&quot;</span>,<span style="color: #483d8b;">&quot;cap&quot;</span>,<span style="color: #483d8b;">&quot;zebra&quot;</span>,<span style="color: #483d8b;">&quot;Blizzard&quot;</span>,<span style="color: #483d8b;">&quot;0xB4DC0DE&quot;</span>,<span style="color: #483d8b;">&quot;!&quot;</span><span style="color: black;">&#93;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">reduce</span><span style="color: black;">&#40;</span><span style="color: #ff7700;font-weight:bold;">lambda</span> x,y: y <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #008000;">len</span><span style="color: black;">&#40;</span>y<span style="color: black;">&#41;</span> <span style="color: #66cc66;">&gt;</span> <span style="color: #008000;">len</span><span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">else</span> x, a<span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;"># OUT: 0xB4DC0DE</span></pre></td></tr></table></div>


<p>And that's all for now. If you're in SE 2014 reading this and don't think you need to know how to use lambda functions - have fun with scheme.</p>
]]></content:encoded>
			<wfw:commentRss>http://jamie-wong.com/2009/12/06/lambda-functions/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
