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

<channel>
	<title>Kerflyn&#039;s Blog</title>
	<atom:link href="http://kerflyn.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://kerflyn.wordpress.com</link>
	<description>Well... It&#039;s a blog!</description>
	<lastBuildDate>Wed, 11 Jan 2012 06:22:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='kerflyn.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Kerflyn&#039;s Blog</title>
		<link>http://kerflyn.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://kerflyn.wordpress.com/osd.xml" title="Kerflyn&#039;s Blog" />
	<atom:link rel='hub' href='http://kerflyn.wordpress.com/?pushpress=hub'/>
		<item>
		<title>From Optional to Monad with Guava</title>
		<link>http://kerflyn.wordpress.com/2011/12/05/from-optional-to-monad-with-guava/</link>
		<comments>http://kerflyn.wordpress.com/2011/12/05/from-optional-to-monad-with-guava/#comments</comments>
		<pubDate>Sun, 04 Dec 2011 22:16:16 +0000</pubDate>
		<dc:creator>fsarradin</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[functional programming]]></category>
		<category><![CDATA[Guava]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[monad]]></category>
		<category><![CDATA[optional]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://kerflyn.wordpress.com/?p=480</guid>
		<description><![CDATA[Guava is a kind of Swiss Army knife API proposed by Google for Java 5 and more. It contains many functionalities that help the developer in its every day life. Guava proposes also a basic functional programming API. You can represent almost statically typed functions with it, map functions on collections, compose them, etc. Since [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=480&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Guava is a kind of Swiss Army knife API proposed by Google for Java 5 and more. It contains many functionalities that help the developer in its every day life. Guava proposes also a basic functional programming API. You can represent almost statically typed functions with it, map functions on collections, compose them, etc. Since its version 10.0, Guava has added a new class called <a href="http://docs.guava-libraries.googlecode.com/git-history/v10.0.1/javadoc/com/google/common/base/Optional.html"><code>Optional</code></a>. It&#8217;s an equivalent to the types <code>Option</code> in Scala or <code>Maybe</code> in Haskell. <code>Optional</code> aims to represent the existence of a value or not. In a sense, this class is a generalization of the <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">Null Object pattern</a>.</p>
<p>In this article, we see the <code>Optional</code> class in action through two use cases involving <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Map.html"><code>java.util.Map</code></a> instances. The first use case is a very basic one. It shows how to use the <code>Optional</code> class. The second use case is based on a problem I&#8217;ve met in a <em>real</em> project. We&#8217;ll see if <code>Optional</code> is helpful in this case.</p>
<h2>Optional vs. null</h2>
<p>Suppose that you want to get a value from a <code>Map</code>. The value is supposed to be located under the key <code>"a"</code>, but you aren&#8217;t sure. In the case where the key <code>"a"</code> doesn&#8217;t exist, the Map implementation is supposed to return <code>null</code>. But, you want to continue with a default value.</p>
<p>Here, you have two solutions. This one</p>
<p><pre class="brush: java;">
Integer value = map.get(&quot;a&quot;);
if (value == null) {
    value = DEFAULT;
}
process(value);
</pre></p>
<p>And, this one</p>
<p><pre class="brush: java;">
Integer value = map.get(&quot;a&quot;);
process(value == null ? DEFAULT : value);
</pre></p>
<p>In order to use the <code>Optional</code> class, we need to define a new accessor for <code>Map</code> instances.</p>
<p><pre class="brush: java;">
public static &lt;K, V&gt; Optional&lt;V&gt; getFrom(Map&lt;K, V&gt; map, K key) {
    V value = map.get(key);
    if (value == null) return Optional.absent();
    else return Optional.of(value);
}
</pre></p>
<p>We notice that you can instantiate Optional by different ways: 1/ by a call to <code>Optional.absent()</code> if there is nothing to return (except the <code>Optional</code> instance), 2/ by of call to <code>Optional.of(value)</code> if you want to return a value. It sounds logical that an accessor to <code>Map</code> returns an <code>Optional</code>, because you aren&#8217;t sure that the given key exists in the <code>Map</code> instance.</p>
<p>Below is the same program but using <code>Optional</code> class.</p>
<p><pre class="brush: java;">
process(getFrom(map, &quot;a&quot;).or(DEFAULT));
</pre></p>
<p>With this code, we don&#8217;t see <code>null</code> anymore.</p>
<h2>Going further: Optional to the limit</h2>
<p>Now, we suppose that we develop a application based on a set of products differentiated by a unique identifier. The products are organized by product identifier, supplier, city, and country. In order to stock these products, imbricated <code>Map</code> are used: the first level uses the country, the second level uses the city, the third level uses the supplier, and the fourth level uses the product identifier to give access to the product. Here is the code you get with no use of <code>Optional</code> class (please, don&#8217;t do this at work! Seriously, don&#8217;t do this!)</p>
<p><pre class="brush: java;">
public Product getProductFrom(
  Map&lt;String, Map&lt;String, Map&lt;String, Map&lt;String, Product&gt;&gt;&gt;&gt; productsByCountry,
  String country, String city, String supplier, String code) {

    Map&lt;String, Map&lt;String, Map&lt;String, Product&gt;&gt;&gt; productsByCity = productsByCountry.get(country);
    if (productsByCity != null) {
        Map&lt;String, Map&lt;String, Product&gt;&gt; productsBySupplier = productsByCity.get(city);
        if (productsBySupplier != null) {
            Map&lt;String, Product&gt; productsByCode = productsBySupplier.get(supplier);
            if (productsByCode != null) {
                return productByCode.get(code);
            }
        }
    }
    return null;
}
</pre></p>
<p>This doesn&#8217;t sounds great, is it?</p>
<p>Now, below is the solution using <code>Optional</code> class.</p>
<p><pre class="brush: java;">
public Optional&lt;Product&gt; getProductFrom(
  Map&lt;String, Map&lt;String, Map&lt;String, Map&lt;String, Product&gt;&gt;&gt;&gt; productsByCountry,
  String country, String city, String supplier, String code) {

    Optional&lt;Map&lt;String, Map&lt;String, Map&lt;String, Product&gt;&gt;&gt;&gt; productsByCity
        = getFrom(productsByCountry, country);
    if (productsByCity.isPresent()) {
        Optional&lt;Map&lt;String, Map&lt;String, Product&gt;&gt;&gt; productsBySupplier
            = getFrom(productsByCity.get(), city);
        if (productsBySupplier.isPresent()) {
            Optional&lt;Map&lt;String, Product&gt;&gt; productsByCode
                = getFrom(productsBySupplier.get(), supplier);
            if (productsByCode.isPresent()) {
                return getFrom(productByCode.get(), code);
            }
        }
    }
    return Optional.absent();
}
</pre></p>
<p>It looks ugly too!</p>
<p>In a view to simplified this implementation, I propose to introduce the notion of monad.</p>
<h2>Option(al) monad</h2>
<p>A <strong>monad</strong> is a programming structure with two operations: <em>unit</em> and <em>bind</em>. Applied to the <code>Optional</code> class, <strong>unit</strong> converts a value into an <code>Optional</code> instance and <strong>bind</strong> applied to an <code>Optional</code> a function from value to <code>Optional</code>. Below, you&#8217;ve there definitions in Java:</p>
<p><pre class="brush: java;">
public class OptionalMonad {
    public static &lt;T&gt; Optional&lt;T&gt; unit(T value) {
        return Optional.of(value);
    }

    public static &lt;T, U&gt; Optional&lt;U&gt; bind(
            Optional&lt;T&gt; value,
            Function&lt;T, Optional&lt;U&gt;&gt; function) {
        if (value.isPresent()) return function.apply(value.get());
        else return Optional.absent();
    }
}
</pre></p>
<p>Notice that bind checks the presence of a value before to apply the function.</p>
<p>Now, to be used by our example in the section above, we need to define a function that will be used as parameter for the bind operator. This function is based on the method <code>getFrom</code>, previously defined, which gives access to a value of a <code>Map</code> from a given key.</p>
<p><pre class="brush: java;">
public static &lt;K, V&gt; Function&lt;Map&lt;K, V&gt;, Optional&lt;V&gt;&gt; getFromKey(final K key) {
    return new Function&lt;Map&lt;K, V&gt;, Optional&lt;V&gt;&gt;() {
        @Override
        public Optional&lt;V&gt; apply(Map&lt;K, V&gt; map) {
            return getFrom(map, key);
        }
    };
}
</pre></p>
<p>Here is the new code</p>
<p><pre class="brush: java;">
public Optional&lt;Product&gt; getProductFrom(
  Map&lt;String, Map&lt;String, Map&lt;String, Map&lt;String, Product&gt;&gt;&gt;&gt; productsByCountry,
  String country, String city, String supplier, String code) {

    Optional&lt;Map&lt;String, Map&lt;String, Map&lt;String, Product&gt;&gt;&gt;&gt; productsByCity
        = bind(unit(productsByCountry), Maps2.&lt;String, Map&lt;String, Map&lt;String, Map&lt;String, Product&gt;&gt;&gt;&gt;getFromKey(country));
    Optional&lt;Map&lt;String, Map&lt;String, Product&gt;&gt;&gt; productsBySupplier
        = bind(productsByCity, Maps2.&lt;String, Map&lt;String, Map&lt;String, Product&gt;&gt;&gt;getFromKey(city));
    Optional&lt;Map&lt;String, Product&gt;&gt; productsByCode
        = bind(productsBySupplier, Maps2.&lt;String, Map&lt;String, Product&gt;&gt;getFromKey(supplier));
    Optional&lt;Product&gt; product
        = bind(productsByCode, Maps2.&lt;String, Product&gt;getFromKey(code));

    return product;
}
</pre></p>
<p>Or more directly</p>
<p><pre class="brush: java;">
public Optional&lt;Product&gt; getProductFrom(
  Map&lt;String, Map&lt;String, Map&lt;String, Map&lt;String, Product&gt;&gt;&gt;&gt; productsByCountry,
  String country, String city, String supplier, String code) {

  return bind(bind(bind(bind(unit(productsByCountry),
    Maps2.&lt;String, Map&lt;String, Map&lt;String, Map&lt;String, Product&gt;&gt;&gt;&gt;getFromKey(country)),
    Maps2.&lt;String, Map&lt;String, Map&lt;String, Product&gt;&gt;&gt;getFromKey(city)),
    Maps2.&lt;String, Map&lt;String, Product&gt;&gt;getFromKey(supplier)),
    Maps2.&lt;String, Product&gt;getFromKey(code));
}
</pre></p>
<p>OK! It&#8217;s weird too. We have to &#8216;fight&#8217; with inline recursive calls of the <code>bind</code> method and also with Java generics. The Java type inference system isn&#8217;t sufficiently powerful to guess them. To reduce occurrences of generics in this code, we could have written a specific version of <code>getFromKey</code> method for each part of the given <code>Map</code>: <code>getFromCountry</code>, <code>getFromCity</code>, <code>getFromSupplier</code>, etc. This moves and distributes the complexity of the code in those methods.</p>
<p><pre class="brush: java;">
public Map&lt;String, Map&lt;String, Map&lt;String, Product&gt;&gt;&gt; getFromCountry(String country) {
  // type inference system knows what to do here
  return Maps2.getFromKey(country);
}

// declaration of the other methods here
// ...

public Optional&lt;Product&gt; getProductFrom(
  Map&lt;String, Map&lt;String, Map&lt;String, Map&lt;String, Product&gt;&gt;&gt;&gt; productsByCountry,
  String country, String city, String supplier, String code) {

  return bind(
    bind(
      bind(
        bind(
          unit(productsByCountry),
          getFromCountry(country)),
          getFromCity(city)),
          getFromSupplier(supplier)),
          getFromCode(code));
}
</pre></p>
<p>The positive side lies into the fact that the <em>if</em> imbrications have disappeared and the code is linear. Notice that due to the <code>bind</code> operator, if one of those call to <code>getFromKey</code> method returns an <code>Optional.absent()</code>, then all the following call to <code>bind</code> will also return an <code>Optional.absent()</code>.</p>
<h2>Is there an happy end for this?</h2>
<p>It&#8217;s difficult to do something better in Java by using the <code>Optional</code> class (unless you have better solution). By considering another JVM language, you&#8217;ve below a solution in Scala.</p>
<p><pre class="brush: scala;">
def getProductFrom(products: Map[String, Map[String, Map[String, Map[String, Product]]]],
                   country: String, city: String, supplier: String, code: String): Option[Product] = {
  for (
    cities &lt;- products.get(country);
    suppliers &lt;- cities.get(city);
    codes &lt;- vendors.get(supplier);
    product &lt;- codes.get(code)
  ) yield product
}
</pre></p>
<p>Here, the <code>for</code> structure provides syntactic sugar to do something close to imperative programming. But in fact, each line in this <code>for</code> structure does the same thing as our previous implementations using the <code>bind</code> operator. The <code>get</code> method here acts the same way as our <code>getFrom</code> method by returning an instance of the type <code>Option</code>. The type <code>Option</code> in Sala is equivalent to the type <code>Optional</code> in Guava. So when you call our Scala version of <code>getProductFrom</code>, if all your parameters appears in the <code>Map</code>, it returns a product. But if one of the parameter isn&#8217;t present, you get the default value.</p>
<p>In Other JVM languages proposes the safe-navigation or null-safe operator <code>value?.method()</code>, like in <a href="http://docs.codehaus.org/display/GROOVY/Operators#Operators-SafeNavigationOperator%28%3F.%29">Groovy</a>, in <a href="http://fantom.org/doc/docLang/Expressions.html#safeInvoke">Fantom</a>, in <a href="http://gosu-lang.org/doc/wwhelp/wwhimpl/api.htm?&amp;context=gosu&amp;src=expressions&amp;topic=Handling_Null_Values_In_Expressions">Gosu</a>, etc. It checks if the value isn&#8217;t <code>null</code> before calling the method.</p>
<p><pre class="brush: java;">
// get a product or null
product = products?.get(country)?.get(city)?.get(supplier)?.get(code)
</pre></p>
<p>For the kind of problems presented in this post, the null-safe operator does a better job than the monad approach. In fact, monads represent a programming structure with a really wider scope. Associated with types other than <code>Optional</code>, you can extend the application field of monads and get the necessary expressivity to explore non-determinism, concurrent programming, handle of errors, etc.</p>
<h2>Conclusion</h2>
<p>So, we&#8217;ve seen the class <code>Optional</code> provided by Guava in two use cases. For the simple case, we&#8217;ve seen how <code>Optional</code> helps to make null reference disappears. But for the complex case, we&#8217;ve seen that <code>Optional</code> alone provides no real advantage. <code>Optional</code> class can make the approach a little easier if we introduce the notion of <code>Optional</code> monad. Thereby, not only the null references disappear but also the recursive if structure. But, we have to fight with the Java generics. And even after this, the code is still hard to read.</p>
<p>It seems clear that to explore a recursive data structure made of <code>Map</code> with Java, you have to choose between to fight with if statements or to fight with generics. But, Java may be not the good language for this kind of problem. In other hand, you should ask yourself if using such a structure is a judicious choice?</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kerflyn.wordpress.com/480/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kerflyn.wordpress.com/480/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kerflyn.wordpress.com/480/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kerflyn.wordpress.com/480/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kerflyn.wordpress.com/480/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kerflyn.wordpress.com/480/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kerflyn.wordpress.com/480/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kerflyn.wordpress.com/480/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kerflyn.wordpress.com/480/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kerflyn.wordpress.com/480/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kerflyn.wordpress.com/480/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kerflyn.wordpress.com/480/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kerflyn.wordpress.com/480/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kerflyn.wordpress.com/480/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=480&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kerflyn.wordpress.com/2011/12/05/from-optional-to-monad-with-guava/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa3d0249159281beafb1f149889c2dd4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kerflyn</media:title>
		</media:content>
	</item>
		<item>
		<title>Implementing the Factorial Function Using Java and Guava</title>
		<link>http://kerflyn.wordpress.com/2011/11/16/implementing-the-factorial-function-using-java-and-guava/</link>
		<comments>http://kerflyn.wordpress.com/2011/11/16/implementing-the-factorial-function-using-java-and-guava/#comments</comments>
		<pubDate>Wed, 16 Nov 2011 06:31:58 +0000</pubDate>
		<dc:creator>fsarradin</dc:creator>
				<category><![CDATA[Functional programming]]></category>
		<category><![CDATA[factorial]]></category>
		<category><![CDATA[functional programming]]></category>
		<category><![CDATA[Guava]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://kerflyn.wordpress.com/?p=499</guid>
		<description><![CDATA[What I like with factorial function is that it&#8217;s easy to implement by using different approaches. This month, I&#8217;ve presented functional programming and some of its main concepts (recursion, tail recursion optimization, list processing) through different ways to code the factorial function. After the presentation, I&#8217;ve asked the audience to implement the factorial by using [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=499&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>What I like with factorial function is that it&#8217;s easy to implement by using different approaches. This month, I&#8217;ve presented functional programming and some of its main concepts (recursion, tail recursion optimization, list processing) through different ways to code the factorial function. After the presentation, I&#8217;ve asked the audience to implement the factorial by using a recursive and a tail recursive approaches, with Java alone, then with Guava&#8217;s <a href="http://docs.guava-libraries.googlecode.com/git-history/v10.0.1/javadoc/index.html"><code>Function</code></a> interface.</p>
<p>In this post, we see the solutions of the exercises I&#8217;ve proposed and some explanation about the functional programming concepts used.</p>
<h2>Factorial</h2>
<p>Here is a reminder of the behavior of the factorial:</p>
<blockquote><p>
The factorial of a given integer n (or n!) is the product of the integers between 1 and n.
</p></blockquote>
<p>In imperative style, you write the factorial like this:</p>
<p><pre class="brush: java;">
public static int factorial(int n) {
    int result = 1;
    for (int i = 1; i &lt;= n; i++) {
        result *= i;
    }
    return result;
}
</pre></p>
<h2>The recursive solution in Java</h2>
<p>The previous implementation of factorial is based explicitly on state manipulation: the variable <code>result</code> is changed successively in the for loop at each iteration. The functional approach dislike particularly the explicit manipulation of a state in the body of a function. Usually, functional programming prohibits the use of loops like for, while, repeat, etc., for this reason. The only way to express a loop is to use recursion (ie. a function that calls itself).</p>
<p>In Mathematics, you express the factorial recursively like this:</p>
<blockquote><p>
0! = 1<br />
n! = n . (n &#8211; 1), for n &gt; 0
</p></blockquote>
<p>Or in plain English:</p>
<blockquote><p>
The factorial of 0 is 1 and the factorial of n is the product between n and the factorial of the preceding integer.
</p></blockquote>
<p>The implementation in Java of the recursive factorial is closed to the mathematic definition:</p>
<p><pre class="brush: java;">
public static int factorial(int n) {
    if (n == 0) return 1;
    else return n * factorial(n - 1);
}
</pre></p>
<h2>Recursive solution in Guava</h2>
<p>Guava proposes a function representation as object. It&#8217;s based on the generic interface <code>Function&lt;T, R&gt;</code>. It looks like this very simple implementation:</p>
<p><pre class="brush: java;">
public interface Function&lt;T, R&gt; {
    R apply(T value);
}
</pre></p>
<p>T is the input type and R the returned type of the function. If you create an instance based on the interface Function, you&#8217;ve to defined the method apply(), that represents the body of the function. Here&#8217;s the implementation of the recursive version of factorial based on Guava:</p>
<p><pre class="brush: java;">
Function&lt;Integer, Integer&gt; factorial = new Function&lt;Integer, Integer&gt;() {
    @Override public Integer apply(Integer n) {
        if (n == 0) return 1;
        else return n * apply(n - 1);
    }
};
</pre></p>
<p>If you want to use this function, you&#8217;ve to write this:</p>
<p><pre class="brush: java;">
Integer result = factorial.apply(5);
</pre></p>
<p>The Guava approach has this particularity to allow you to declare recursive and anonymous functions:</p>
<p><pre class="brush: java;">
Integer result = new Function&lt;Integer, Integer&gt;() {
    @Override public Integer apply(Integer n) {
        if (n == 0) return 1;
        else return n * apply(n - 1);
    }
}.apply(5);
</pre></p>
<h2>Tail recursion in Java</h2>
<p>There&#8217;s another way to implement the recursive version of the factorial. This approach consists in having the recursive call executed just before to return from the function. There must have no other instruction to execute between the recursive call and the return instruction. This approach is called <strong>tail recursion</strong>. The previous implementation isn&#8217;t a case of tail recursion, because you have to execute a multiplication between n and the value returned by the recursive call before to exit the function.</p>
<p>In order to implement a tail recursive factorial, we have to introduce a second parameter (named k) to the function. This parameter contains the partial result of the function through the successive recursive calls. Once the stop condition is reached, k contains the final result. Below, you&#8217;ve the implementation of the tail recursive factorial:</p>
<p><pre class="brush: java;">
private static int fact(int n, int k) {
    if (n == 0) return k;
    else return fact(n - 1, n * k);
}

public static int factorial(int n) {
    return fact(n, 1);
}
</pre></p>
<p>Notice that for the first call, the parameter k is initialized to 1. This relates to the basis case: when n is 0 then the function should return 1.</p>
<h2>Motivation behind the tail recursion</h2>
<p>There&#8217;s an important difference in behavior between the recursive and the tail recursive implementations. These difference is visible through the the call stack. In the recursive case, the result is built as you come back from recursive calls. Here is the different states of the call stack in recursive version when we call <code>factorial(5)</code>:</p>
<p><pre class="brush: plain;">
-&gt; factorial(5)  // first call
  -&gt; factorial(4)
    -&gt; factorial(3)
      -&gt; factorial(2)
        -&gt; factorial(1)
          -&gt; factorial(0)  // here, we've reached the stop condition
          &lt;- 1
        &lt;- 1 = 1 * 1  // all remaining multiplications are executed
      &lt;- 2 = 2 * 1
    &lt;- 6 = 3 * 2
  &lt;- 24 = 4 * 6
&lt;- 120 = 5 * 24  // we have computed the result in the last return
</pre></p>
<p>Now, you can see the call stack for the tail recursive implementation for the same call:</p>
<p><pre class="brush: plain;">
-&gt; fact(5, 1)  // first call
  -&gt; fact(4, 5)  // result is built through the successive calls
    -&gt; fact(3, 20)
      -&gt; fact(2, 60)
        -&gt; fact(1, 120)
          -&gt; fact(0, 120)  // here, we've reached the stop condition
          &lt;- 120  // the final result is obtained directly in the last recursive call
        &lt;- 120
      &lt;- 120
    &lt;- 120
  &lt;- 120
&lt;- 120
</pre></p>
<p>You can notice that when we&#8217;re coming back from the recursive calls here, the same value is returned. Thus, we can easily imagine to optimize the tail recursive implementation. In fact, there two possible optimizations at this level. The first one is call <em>trampolining</em>. It consists in generating some small modification where recursive call is marked <em>bounce</em> and return is marked <em>landing</em>. Then an external fonction is used to emulate the recursive calls based on a while loop.</p>
<p>The second optimization uses a deeper transformation of the source code, where the while loop is directly put inside the function body. For the tail recursive implementation of the factorial function, this second optimization would turn our source code into this:</p>
<p><pre class="brush: java;">
public static int factorial(int n, int k) {
    while (!(n == 0)) {
        k = n * k;
        n = n - 1;
    }
    return k;
}
</pre></p>
<p>These optimizations prevent the deep use of the call stack. Thus, you have no occurrence of stack overflow. But, you might have an infinite loop if you mistype the stop condition. The advantage of the second optimization over the first one and all recursive implementations is that it&#8217;s really quick as there&#8217;s no use of the call stack. A language like Scala proposes this second optimization by default. A precise look at the produced bytecode shows the transformation of the recursive call into a goto.</p>
<p>These optimizations aren&#8217;t present in Java.</p>
<p>Notice that not all recursive functions can be converted to a tail recursive function. This is the case of the function that computes the Fibonnacci series. It based on the jonction of two recursive calls.</p>
<p><pre class="brush: java;">
public static fib(int n) {
    if (n &lt;= 1) return 1;
    else return fib(n-1) + fib(n-2);
}
</pre></p>
<h2>Tail recursion in Guava</h2>
<p>We&#8217;ve seen that the tail recursive implementation of the factorial needs two parameters. But in Guava, you can only define functions that accept a unique argument! So how do we do to transform a function of one argument into a function of two arguments?</p>
<p>There are two possibilities. The first one consists in creating a class that represents a pair of elements. Thus a function that takes two arguments is equivalent to a function that takes a pair of elements. The second possibility consists in using the curryfication. The <strong>curryfication</strong> is a use case of the higher order functions. With this, a function that takes many arguments is converted into a function that takes the first argument, and return a function that takes the second argument, and so on till we get the last argument. For example, the addition function (<code>add</code>) is typically a function of two arguments (<code>a</code> and <code>b</code>). You can write <code>add</code> in such a way that <code>add</code> takes <code>a</code> and return a function that waits for <code>b</code>. Once you get <code>b</code>, the function is evaluated. The interest of such an approach isn&#8217;t to force you to provide all parameters of a function at the same time. For our <code>add</code> function, you can use <code>add</code> directly to execute an addition: <code>add.apply(1).apply(3) == 4</code>. Or you can use <code>add</code> to define the function <code>add_one</code> just by providing the first parameter only: <code>add_one = add.apply(1)</code>. Then, you can provide the second parameter when you want through <code>add_one</code>: <code>add_one.apply(3) == 4</code>.</p>
<p>Below is the implementation of tail recursive factorial based on Guava. The signature of this function is <code>Function&lt;Integer, Function&lt;Integer, Integer&gt;&gt;</code>. Here, you&#8217;ve to understand:</p>
<blockquote><p>factorial is a function that takes a first parameter n and returns another function that takes a second parameter k and returns the factorial of n.
</p></blockquote>
<p><pre class="brush: java;">
public class FactorialFunction implements Function&lt;Integer, Function&lt;Integer, Integer&gt;&gt; {
    @Override
    Function&lt;Integer, Integer&gt; apply(final Integer n) {
        return new Function&lt;Integer, Integer&gt;() {
            @Override
            public Integer apply(Integer k) {
                if (n == 0) return k;
                else return FactorialFunction.this.apply(n - 1).apply(k * n);
            }
        };
    }
}

FactorialFunction fact = new FactorialFunction();
Integer result = fact.apply(5).apply(1); // factorial of 5
</pre></p>
<p>Notice the use of <code>FactorialFunction.this</code> in order to use the outer object in the inner one. You have to reference the outer object in order to set all parameters before the recursive call. This forces you to create a named class to represent your factorial function.</p>
<p>Compare this implementation with the implementation below in Haskell, which is tail recursive and curryfied already. They&#8217;re both equivalent:</p>
<p><pre class="brush: plain;">
fact n k = if n == 0
  then k
  else fact (n-1) (n*k)
</pre></p>
<p>In fact, there are differences in the Guava implementation: it isn&#8217;t optimized and you create a new object for each recursive call.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kerflyn.wordpress.com/499/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kerflyn.wordpress.com/499/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kerflyn.wordpress.com/499/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kerflyn.wordpress.com/499/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kerflyn.wordpress.com/499/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kerflyn.wordpress.com/499/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kerflyn.wordpress.com/499/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kerflyn.wordpress.com/499/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kerflyn.wordpress.com/499/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kerflyn.wordpress.com/499/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kerflyn.wordpress.com/499/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kerflyn.wordpress.com/499/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kerflyn.wordpress.com/499/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kerflyn.wordpress.com/499/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=499&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kerflyn.wordpress.com/2011/11/16/implementing-the-factorial-function-using-java-and-guava/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa3d0249159281beafb1f149889c2dd4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kerflyn</media:title>
		</media:content>
	</item>
		<item>
		<title>Instantiate in Java with the Scala&#8217;s Way</title>
		<link>http://kerflyn.wordpress.com/2011/11/09/instantiate-in-java-with-the-scalas-way/</link>
		<comments>http://kerflyn.wordpress.com/2011/11/09/instantiate-in-java-with-the-scalas-way/#comments</comments>
		<pubDate>Tue, 08 Nov 2011 22:22:31 +0000</pubDate>
		<dc:creator>fsarradin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[case class]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[type inference]]></category>

		<guid isPermaLink="false">http://kerflyn.wordpress.com/?p=491</guid>
		<description><![CDATA[Case classes in Scala facilitate the instantiation by removing the use of the keyword new. It isn&#8217;t a big invention, but it helps to have a source code more readable. Especially when you imbricate these instantiations one in another. The force of Scala&#8217;s case classes is to provide a way to practice symbolic computation &#8212; [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=491&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Case classes in Scala facilitate the instantiation by removing the use of the keyword <code>new</code>. It isn&#8217;t a big invention, but it helps to have a source code more readable. Especially when you imbricate these instantiations one in another. The force of Scala&#8217;s case classes is to provide a way to practice symbolic computation &#8212; in my post named <a href="http://kerflyn.wordpress.com/2011/02/14/playing-with-scalas-pattern-matching/">Playing with Scala’s pattern matching</a>, read the section <em>Advanced pattern matching: case class</em>.</p>
<p>Suppose that you want to declare a type that represents a pair of elements. We don&#8217;t know the type of these elements and they may have different types. In Scala, you&#8217;ll write something like this:</p>
<p><pre class="brush: scala;">
case class Pair[T1, T2](first: T1, second: T2)

// usage: val myPair = Pair(1, 2)
</pre></p>
<p>The implementation in Java below is a (hugely) simplified equivalent to the implementation in Scala:</p>
<p><pre class="brush: java;">
public class Pair&lt;T1, T2&gt; {
    private T1 first;
    private T2 second;

    public Pair(T1 first, T2 second) {
        this.first = first;
        this.second = second;
    }

    public static &lt;T1, T2&gt; Pair&lt;T1, T2&gt; Pair(T1 first, T2 second) {
        return new Pair(first, second);
    }
}
</pre></p>
<p>Here is an example where I design a binary tree structure with the help of the Java version of <code>Pair</code>. Notice that with this approach, I don&#8217;t have to use the diamond declaration in the instantiation (ie. <code>Pair&lt;Integer, Pair&lt;String, ...&gt;&gt;</code>). It&#8217;s automatically determined by the type inference algorithm.</p>
<p><pre class="brush: java;">
Pair&lt;Integer, Pair&lt;String, Pair&lt;Boolean, Object&gt;&gt;&gt; tree
  = Pair(1,
      Pair(&quot;hello&quot;,
        Pair(true, new Object())));
</pre></p>
<p>Now, you can say it&#8217;s really helpful!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kerflyn.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kerflyn.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kerflyn.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kerflyn.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kerflyn.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kerflyn.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kerflyn.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kerflyn.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kerflyn.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kerflyn.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kerflyn.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kerflyn.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kerflyn.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kerflyn.wordpress.com/491/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=491&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kerflyn.wordpress.com/2011/11/09/instantiate-in-java-with-the-scalas-way/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa3d0249159281beafb1f149889c2dd4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kerflyn</media:title>
		</media:content>
	</item>
		<item>
		<title>My First Coding Dojo</title>
		<link>http://kerflyn.wordpress.com/2011/09/22/my-first-coding-dojo/</link>
		<comments>http://kerflyn.wordpress.com/2011/09/22/my-first-coding-dojo/#comments</comments>
		<pubDate>Thu, 22 Sep 2011 20:51:50 +0000</pubDate>
		<dc:creator>fsarradin</dc:creator>
				<category><![CDATA[Agility]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Clojure]]></category>
		<category><![CDATA[coding dojo]]></category>

		<guid isPermaLink="false">http://kerflyn.wordpress.com/?p=445</guid>
		<description><![CDATA[I took part in a coding dojo. We aimed to find the firsts prime numbers with the help of Clojure. The primary goal was not to solve the prime number problem. In fact, we tried to learn how to program in Clojure, also trying to be as close to the Clojure&#8217;s programming style as we [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=445&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I took part in a coding dojo. We aimed to find the firsts prime numbers with the help of Clojure. The primary goal was not to solve the prime number problem. In fact, we tried to learn how to program in Clojure, also trying to be as close to the Clojure&#8217;s programming style as we could.</p>
<p><a href="http://kerflyn.files.wordpress.com/2011/08/dojo-clojure.jpg"><img class="size-medium wp-image-468 alignnone" title="dojo-clojure" src="http://kerflyn.files.wordpress.com/2011/08/dojo-clojure.jpg?w=300&#038;h=225" alt="Trying to solve the prime number problem with Clojure" width="300" height="225" /></a></p>
<p>Photo by <a href="http://twitter.com/ulrich">Ulrich Vachon</a></p>
<p>We started from a configuration using Cake to manage the project, a text editor, and some unit tests. We&#8217;ve worked by pair, changing one member and switching roles time to time.</p>
<p>I must confess that it isn&#8217;t something easy to think FP and write a program in Clojure. But the cohesion of the group and the overall will to reach the goal made it easier to finally write a program that succeeded all the tests.</p>
<p>So, after 1 hour and 20 minutes, here&#8217;s the result of our dojo :</p>
<p><a href="https://github.com/elefevre/dojo-at-lunch/blob/master/2011-09-21-nombres-premiers/test/prime_numbers/test/core.clj">https://github.com/elefevre/dojo-at-lunch/blob/master/2011-09-21-nombres-premiers/test/prime_numbers/test/core.clj</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kerflyn.wordpress.com/445/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kerflyn.wordpress.com/445/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kerflyn.wordpress.com/445/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kerflyn.wordpress.com/445/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kerflyn.wordpress.com/445/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kerflyn.wordpress.com/445/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kerflyn.wordpress.com/445/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kerflyn.wordpress.com/445/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kerflyn.wordpress.com/445/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kerflyn.wordpress.com/445/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kerflyn.wordpress.com/445/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kerflyn.wordpress.com/445/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kerflyn.wordpress.com/445/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kerflyn.wordpress.com/445/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=445&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kerflyn.wordpress.com/2011/09/22/my-first-coding-dojo/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa3d0249159281beafb1f149889c2dd4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kerflyn</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2011/08/dojo-clojure.jpg?w=300" medium="image">
			<media:title type="html">dojo-clojure</media:title>
		</media:content>
	</item>
		<item>
		<title>Comparing Java APIs for Functional Programming [FR]</title>
		<link>http://kerflyn.wordpress.com/2011/06/30/comparing-java-apis-for-functional-programming-fr/</link>
		<comments>http://kerflyn.wordpress.com/2011/06/30/comparing-java-apis-for-functional-programming-fr/#comments</comments>
		<pubDate>Thu, 30 Jun 2011 19:34:28 +0000</pubDate>
		<dc:creator>fsarradin</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://kerflyn.wordpress.com/?p=435</guid>
		<description><![CDATA[While the Java Community Process (JCP) has announced the appearance of the functional programming in the Java language,  with the introduction of the lambda expressions (JSR 335: Lambda Expressions for the JavaTM Programming Language), is it possible with the current version of Java to practice this paradigm? While writing those lines, the JCP is in a deep [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=435&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>While the Java Community Process (JCP) has announced the appearance of the functional programming in the Java language,  with the introduction of the lambda expressions (<a title="JSR 335: Lambda Expressions for the JavaTM Programming Language" href="http://www.jcp.org/en/jsr/detail?id=335">JSR 335: Lambda Expressions for the JavaTM Programming Language</a>), is it possible with the current version of Java to practice this paradigm? While writing those lines, the JCP is in a deep brainstorming on this topic. There are different propositions about the syntax to adopt for the JSR 335 : a <a title="straw-man proposal" href="http://cr.openjdk.java.net/~mr/lambda/straw-man/">straw-man proposal</a>, a <a title="prototype for OpenJDK" href="http://openjdk.java.net/projects/lambda/">prototype for OpenJDK</a> is in progress, the <a title="BGGA proposal" href="http://www.javac.info/">BGGA proposal</a> (Bracha, Gafter, Gosling, and von der Ahé), etc. But none of these syntaxes have formalized. Nevertheless, a first draft should be available during September 2011 and should appear in 2012 with Java 8.</p>
<p>Till then, there are different APIs that allow the developers to use functional programming with Java and they don&#8217;t have to learn a new the language.</p>
<p><em>My first article on the Xebia&#8217;s blog is available in French: <a href="http://blog.xebia.fr/2011/06/29/comparaison-dapi-java-de-programmation-fonctionnelle/">http://blog.xebia.fr/2011/06/29/comparaison-dapi-java-de-programmation-fonctionnelle/</a></em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kerflyn.wordpress.com/435/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kerflyn.wordpress.com/435/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kerflyn.wordpress.com/435/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kerflyn.wordpress.com/435/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kerflyn.wordpress.com/435/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kerflyn.wordpress.com/435/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kerflyn.wordpress.com/435/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kerflyn.wordpress.com/435/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kerflyn.wordpress.com/435/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kerflyn.wordpress.com/435/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kerflyn.wordpress.com/435/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kerflyn.wordpress.com/435/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kerflyn.wordpress.com/435/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kerflyn.wordpress.com/435/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=435&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kerflyn.wordpress.com/2011/06/30/comparing-java-apis-for-functional-programming-fr/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa3d0249159281beafb1f149889c2dd4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kerflyn</media:title>
		</media:content>
	</item>
		<item>
		<title>How TreeMap can save your day?</title>
		<link>http://kerflyn.wordpress.com/2011/05/20/how-treemap-can-save-your-day/</link>
		<comments>http://kerflyn.wordpress.com/2011/05/20/how-treemap-can-save-your-day/#comments</comments>
		<pubDate>Fri, 20 May 2011 00:59:33 +0000</pubDate>
		<dc:creator>fsarradin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[TreeMap]]></category>

		<guid isPermaLink="false">http://kerflyn.wordpress.com/?p=360</guid>
		<description><![CDATA[In Java collections, the TreeMap is a sorted and navigable map that organizes elements in a self-balancing binary tree. It can help you solve problems like &#8220;Which element in this collection is the closest to this one?&#8221; Introduction You want to plan reservations for a room. Here are some reservations: From 4-Jan to 7-Jan, occupant: Mr. A [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=360&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In Java collections, the <a title="Javadoc: TreeMap" href="http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html">TreeMap</a> is a sorted and navigable map that organizes elements in a self-balancing binary tree. It can help you solve problems like &#8220;Which element in this collection is the closest to this one?&#8221;</p>
<h2>Introduction</h2>
<p>You want to plan reservations for a room. Here are some reservations:</p>
<ul>
<li>From 4-Jan to 7-Jan, occupant: Mr. A</li>
<li>From 10-Jan to 21-Jan, occupant: Mrs. B</li>
<li>From 5-Feb to 18-Feb, occupant: Mr. A</li>
<li>From 20-Feb to 3-Mar, occupant: Mr. C</li>
</ul>
<p>Suppose that there is no possibility for a reservation to override another one. How do you determine in a programmatic way who is the occupant the 10-Feb? And the 19-Feb?</p>
<h2>Algorithm</h2>
<p>There are many possibilities to answer to those questions. Basically, one of them is to store the reservations in a set. When searching for an occupant at a given date, you walk through the set, testing each element. You stop when you have a reservation that contains the given date or when there is no more reservation to test. This is a linear search algorithm. In  the worst case, the time complexity is <em>O</em>(<em>n</em>), ie. when you have to test all elements and there is no matching element or the matching element is the last one.</p>
<p>To improve this algorithm, you can also use a <strong>binary search algorithm</strong>. It consists at each step in dividing the set of elements in two parts and continuing searching in one of those parts. This algorithm needs a set of sorted elements. Its time complexity is <em>O</em>(log(<em>n</em>)) in the worst case. This is better because if you have 7 elements, you will only need 3 tests against 7 for linear search, in the worst case. And if you have 1000 elements, you will only need 10 tests against 1000 for the linear version, in the worst case. However, with the binary search algorithm, you may lost time while sorting elements. Java proposes in classes <a href="http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html">java.util.Arrays</a> and <a href="http://download.oracle.com/javase/6/docs/api/java/util/Collections.html">java.util.Collections</a> the method sort() the uses the <a href="http://en.wikipedia.org/wiki/Merge_sort">merge sort</a> algorithm that guaranties a time complexity of <em>O</em>(<em>n</em>.log(<em>n</em>)). Thus, <em>sorting</em> + <em>binary search</em> is worst than a linear search, that doesn&#8217;t need a sorted set of elements. Note that Java SE proposes implementations of the binary search algorithm in the methods<a href="http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#binarySearch(T[], T, java.util.Comparator)"> java.util.Arrays.binarySearch()</a> and <a href="http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#binarySearch(java.util.List, T)">java.util.Collections.binarySearch()</a>.</p>
<p>Another approach to the binary search is to generate the corresponding <strong>binary tree</strong>. Indeed, the binary search algorithm is like a walk through a height-balanced binary tree. At each step of the algorithm, we select the left part (left branch) or right part (right branch) of the subset of elements (the subtree) according to a central element (a node). But the big difference is that if you apply an algorithm like the <a href="http://en.wikipedia.org/wiki/Red-black_tree">red-black tree</a> for your binary tree, two aspects are guaranteed:</p>
<ol>
<li>Each time you add an element, it is sorted with the rest of the tree.</li>
<li>The tree is height-balanced. It means that its maximal height is <em>O</em>(log(<em>n</em>)).</li>
</ol>
<p>For such a tree, the operations <em>insert</em> and <em>search</em> cost of time is <em>O</em>(log(<em>n</em>)) each.</p>
<p>The class <a href="http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html">java.util.TreeMap</a> represents such a height-balancing binary tree and uses the red-black tree algorithm. But what is even more interesting with this class, is that it provides the methods <a href="http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html#ceilingEntry(K)">ceilingEntry()</a> and <a href="http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html#floorEntry(K)">floorEntry()</a>. They return the map entry which key is the closest respectively after and before the given key.</p>
<h2>Representation of a reservation</h2>
<p>Below is the source code of a simplified class to represent such reservations. This implementation uses <a href="http://code.google.com/p/guava-libraries/">guava</a>.</p>
<p><pre class="brush: java;">
public class Reservation {
    public Date from;
    public Date to;
    public String occupant;

    public Reservation(Date from, Date to, String occupant) {
        this.from = from;
        this.to = to;
        this.occupant = occupant;
    }

    public boolean contains(Date date) {
        return !(from.after(date) || to.before(date));
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
            .add(&quot;from&quot;, from)
            .add(&quot;to&quot;, to)
            .add(&quot;occupant&quot;, occupant)
            .toString();
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(from, to, occupant);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || !(obj instanceof Reservation)) {
            return false;
        }
        Reservation reservation = (Reservation) obj;
        return Objects.equals(from, reservation.from)
            &amp;&amp; Objects.equals(to, reservation.to)
            &amp;&amp; Objects.equals(occupant, reservation.occupant);
    }

}
</pre></p>
<p>We declare below all four reservations that you can find in the introduction at the top of the post.</p>
<p><pre class="brush: java;">
Date from, to;
Calendar calendar = Calendar.getInstance();

calendar.set(2011, 0, 4);
from = calendar.getTime();
calendar.set(2011, 0, 7);
to = calendar.getTime();
Reservation reserv1MrA = new Reservation(from, to, &quot;Mr. A&quot;);

calendar.set(2011, 0, 10);
from = calendar.getTime();
calendar.set(2011, 0, 21);
to = calendar.getTime();
Reservation reserv1MrsB = new Reservation(from, to, &quot;Mrs. B&quot;);

calendar.set(2011, 1, 5);
from = calendar.getTime();
calendar.set(2011, 1, 18);
to = calendar.getTime();
Reservation reserv2MrA = new Reservation(from, to, &quot;Mr. A&quot;);

calendar.set(2011, 1, 20);
from = calendar.getTime();
calendar.set(2011, 2, 3);
to = calendar.getTime();
Reservation reserv1MrC = new Reservation(from, to, &quot;Mr. C&quot;);
</pre></p>
<p><span class="Apple-style-span" style="font-size:20px;font-weight:bold;">How to find a reservation from a given date</span></p>
<p>I group a set of reservations in a class that I&#8217;ve called Planning. Once instantiated, you can add reservations (method add()) and you can get a reservation at a given date (method getReservationAt()).</p>
<p>There are two steps to get a reservation close to a date.</p>
<ol>
<li>I first use the method <a href="http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html#floorEntry(K)">floorEntry()</a>. It gets you the map entry which key is the greatest one less than the given date.</li>
<li>Second, I check if the reservation (that is the value of the entry) contains the given date.</li>
</ol>
<p><pre class="brush: java;">
public class Planning {
    public final TreeMap&lt;Date, Reservation&gt; reservations;

    public Planning() {
        reservations = new TreeMap&lt;Date, Reservation&gt;();
    }

    public void add(Reservation reservation) {
        reservations.put(reservation.from, reservation);
    }

    public Reservation getReservationAt(Date date) {
        Entry&lt;Date, Reservation&gt; entry = reservations.floorEntry(date);
        if (entry == null) {
            return null;
        }
        Reservation reservation = entry.getValue();
        if (!reservation.contains(date)) {
            return null;
        }
        return reservation;
    }
}
</pre></p>
<h2>Test</h2>
<p>We first store the reservations declared above in a planning.</p>
<p><pre class="brush: java;">
Planning planning = new Planning();
planning.add(reserv1MrA);
planning.add(reserv1MrsB);
planning.add(reserv2MrA);
planning.add(reserv1MrC);
</pre></p>
<p>Now, who has made a reservation the 10-Feb and the 19-Feb? (Here, I use <a href="http://code.google.com/p/fest/#Fluent_Assertions">FEST-assert</a> as assertion API.)</p>
<p><pre class="brush: java;">
Calendar calendar = Calendar.getInstance();

calendar.set(2011, 1, 10);
Date dateOfMrA = calendar.getTime();
assertThat(planning.getReservationAt(dateOfMrA).occupant).isEqualTo(&quot;Mr. A&quot;);

calendar.set(2011, 1, 19);
Date dateNoReservation = calendar.getTime();
assertThat(planning.getReservationAt(dateNoReservation)).isNull();
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kerflyn.wordpress.com/360/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kerflyn.wordpress.com/360/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kerflyn.wordpress.com/360/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kerflyn.wordpress.com/360/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kerflyn.wordpress.com/360/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kerflyn.wordpress.com/360/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kerflyn.wordpress.com/360/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kerflyn.wordpress.com/360/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kerflyn.wordpress.com/360/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kerflyn.wordpress.com/360/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kerflyn.wordpress.com/360/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kerflyn.wordpress.com/360/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kerflyn.wordpress.com/360/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kerflyn.wordpress.com/360/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=360&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kerflyn.wordpress.com/2011/05/20/how-treemap-can-save-your-day/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa3d0249159281beafb1f149889c2dd4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kerflyn</media:title>
		</media:content>
	</item>
		<item>
		<title>&#8220;Is this point inside this rectangle?&#8221; without IF</title>
		<link>http://kerflyn.wordpress.com/2011/05/04/is-this-point-inside-this-rectangle-without-if/</link>
		<comments>http://kerflyn.wordpress.com/2011/05/04/is-this-point-inside-this-rectangle-without-if/#comments</comments>
		<pubDate>Wed, 04 May 2011 05:01:22 +0000</pubDate>
		<dc:creator>fsarradin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[geometry]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://kerflyn.wordpress.com/?p=374</guid>
		<description><![CDATA[The class Point is given below. The hasCode() method uses an helper that you can find in guava. The method equals() contains the only if in this post (promised ). Here is the class Rectangle: I suppose that start.x &#60; end.x and that start.y &#60; end.y I define the minimum and the maximum of two [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=374&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The class Point is given below. The hasCode() method uses an helper that you can find in <a href="http://code.google.com/p/guava-libraries/">guava</a>. The method equals() contains the only if in this post (promised <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ).</p>
<p><pre class="brush: java;">
public class Point {
    public final int x;
    public final int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(x, y);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null || !(obj instanceof Point)) {
            return false;
        }
        Point point = (Point) obj;
        return x == point.x &amp;&amp; y == point.y;
    }
}
</pre></p>
<p>Here is the class Rectangle:</p>
<p><pre class="brush: java;">
public class Rectangle {
    public final Point start;
    public final Point end;

    public Rectangle(Point start, Point end) {
        this.start = start;
        this.end = end;
    }
}
</pre></p>
<p>I suppose that start.x &lt; end.x and that start.y &lt; end.y</p>
<p>I define the minimum and the maximum of two points as the point which coordinates are respectively the minimum and the maximum of the coordinates of the given points. For example, the minimum of the points (1, 4) and (3, 2) is (1, 2), and the maximum is (3, 4).</p>
<p><pre class="brush: java;">
public class Points {
    // it's an utility class
    private Points() { throw new UnsupportedOperationException(); }

    public static Point min(Point p1, Point p2) {
        return new Point(Math.min(p1.x, p2.x), Math.min(p1.y, p2.y));
    }

    public static Point max(Point p1, Point p2) {
        return new Point(Math.max(p1.x, p2.x), Math.max(p1.y, p2.y));
    }
}
</pre></p>
<p>Now, I give the method Rectangle.contains() that checks if a point is inside a rectangle. The idea is to use the methods min() and max() between the given point and the rectangle edges as filters: if the computed point is different from the given point, then the given point is not in the rectangle.</p>
<p><pre class="brush: java;">
import static Points.*;

public class Rectangle {
    // see code above...

    public boolean contains(Point point) {
        return point.equals(max(start, min(end, point)));
    }
}
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kerflyn.wordpress.com/374/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kerflyn.wordpress.com/374/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kerflyn.wordpress.com/374/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kerflyn.wordpress.com/374/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kerflyn.wordpress.com/374/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kerflyn.wordpress.com/374/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kerflyn.wordpress.com/374/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kerflyn.wordpress.com/374/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kerflyn.wordpress.com/374/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kerflyn.wordpress.com/374/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kerflyn.wordpress.com/374/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kerflyn.wordpress.com/374/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kerflyn.wordpress.com/374/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kerflyn.wordpress.com/374/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=374&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kerflyn.wordpress.com/2011/05/04/is-this-point-inside-this-rectangle-without-if/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa3d0249159281beafb1f149889c2dd4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kerflyn</media:title>
		</media:content>
	</item>
		<item>
		<title>Playing with Scala&#8217;s pattern matching</title>
		<link>http://kerflyn.wordpress.com/2011/02/14/playing-with-scalas-pattern-matching/</link>
		<comments>http://kerflyn.wordpress.com/2011/02/14/playing-with-scalas-pattern-matching/#comments</comments>
		<pubDate>Mon, 14 Feb 2011 16:52:40 +0000</pubDate>
		<dc:creator>fsarradin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[pattern matching]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[switch]]></category>

		<guid isPermaLink="false">http://kerflyn.wordpress.com/?p=159</guid>
		<description><![CDATA[How many times have you been stuck in your frustration because you were unable to use strings as entries in switch-case statements. Such an ability would be really useful for example to analyze the arguments of your application or to parse a file, or any content of a string. Meanwhile, you have to write a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=159&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>How many times have you been stuck in your frustration because you were unable to use strings as entries in switch-case statements. Such an ability would be really useful for example to analyze the arguments of your application or to parse a file, or any content of a string. Meanwhile, you have to write a series of if-else-if statements (and this is annoying). Another solution is to use a hash map, where the keys are those strings and values are the associated reified processes, for example a Runnable or a Callable in Java (but this is not really natural, long to develop, and boring too).</p>
<p>If a switch-case statement that accepts strings as entries would be a revolution for you, the Scala&#8217;s <strong>pattern matching</strong> says that this is not enough! Indeed, there are other cases where a series of if-else-if statements would be generously transformed into a look-alike switch-case statement. For example, it would be really nice to simplify a series of <em>instanceof</em> and cast included in if-else-if to execute the good process according to the type of a parameter.</p>
<p>In this post, we see the power of the Scala&#8217;s pattern matching in different use cases.</p>
<p><em>Notice that the pattern matching is not something new. It is something that appears already in some other languages like OCaml, Haskell. A kind of pattern matching also exits in Prolog, but it uses a far different mechanism (</em>unification<em> in this case).<br />
</em></p>
<h2>Traditional approach</h2>
<p>There is an approach to the Scala&#8217;s pattern matching that looks similar to the switch-case structure in C and Java: each case entry use an integer or any scalar type. Here is an example:</p>
<p><pre class="brush: scala;">
def toYesOrNo(choice: Int): String = choice match {
    case 1 =&gt; &quot;yes&quot;
    case 0 =&gt; &quot;no&quot;
    case _ =&gt; &quot;error&quot;
  }
</pre></p>
<p>So if  you enter toYesOrNo(1), Scala says &#8221;yes&#8221;. And if you enter toYesOrNo(2), Scala says &#8220;error&#8221;. Notice that the symbol _ is used to formulate the default case.You also have to remark that there is no need to use the break statement.</p>
<p>But if you want that Scala says &#8220;yes&#8221; when you enter toYesOrNo(1), toYesOrNo(2), or toYesOrNo(3), you will write the function like this:</p>
<p><pre class="brush: scala;">
def toYesOrNo(choice: Int): String = choice match {
    case 1 | 2 | 3 =&gt; &quot;yes&quot;
    case 0 =&gt; &quot;no&quot;
    case _ =&gt; &quot;error&quot;
  }
</pre></p>
<p>Now, you can use a string for each case entry. Using strings is interesting when you want to parse options of your applications:</p>
<p><pre class="brush: scala;">
def parseArgument(arg: String) = arg match {
    case &quot;-h&quot; | &quot;--help&quot; =&gt; displayHelp
    case &quot;-v&quot; | &quot;--version&quot; =&gt; displayVerion
    case whatever =&gt; unknownArgument(whatever)
  }
</pre></p>
<p>So if you enter parseArgument(&#8220;-h&#8221;) or parseArgument(&#8220;&#8211;help&#8221;), Scala calls the <em>displayHelp</em> function. And if you enter parseArgument(&#8220;huh?&#8221;), Scala calls unknownArgument(&#8220;huh?&#8221;).</p>
<p>Notice that I have not used _ for the default case. Instead, I have put an identifier as its value is used in the associated instruction.</p>
<h2>Typed pattern</h2>
<p>Sometimes in Java, you have to deal with an instance of something that appears like an Object or any high level classes or interfaces. After checking for nullity, you have to use series of if-else statements and instanceof-cast to check the class or the interface that the instance extends or implements, before using it and processing the instance correctly. This the case when you have to override the equals() method in Java. Here is the way Scala sees the thing:</p>
<p><pre class="brush: scala;">
def f(x: Any): String = x match {
    case i:Int =&gt; &quot;integer: &quot; + i
    case _:Double =&gt; &quot;a double&quot;
    case s:String =&gt; &quot;I want to say &quot; + s
  }
</pre></p>
<ul>
<li>f(1) → &#8220;integer: 1&#8243;</li>
<li>f(1.0) → &#8220;a double&#8221;</li>
<li>f(&#8220;hello&#8221;) → &#8220;I want to say hello&#8221;</li>
</ul>
<p>Is not it better than a succession of if+instanceof+cast?</p>
<p>This kind of pattern matching is useful to walk through a structure using the <a href="http://en.wikipedia.org/wiki/Composite_pattern">composite design pattern</a>. For example, you can use it to explore the DOM of an XML document or the object model of a JSON message.</p>
<h2>Functional approach to pattern matching</h2>
<p>A side effect of such a matching is that it provides an alternative way to design functions. For example, consider the factorial function. If you choose the recursive version, usually, you would define it like this:</p>
<p><pre class="brush: scala;">
def fact(n: Int): Int =
    if (n == 0) 1
    else n * fact(n - 1)
</pre></p>
<p>But you can use Scala&#8217;s pattern matching in this case:</p>
<p><pre class="brush: scala;">
def fact(n: Int): Int = n match {
    case 0 =&gt; 1
    case n =&gt; n * fact(n - 1)
  }
</pre></p>
<p>Notice the use of the variable <em>n</em> in this case. It is matched with any value that does not appears in the preceding cases. You have to understand that the <em>n</em> in the last case is not the same as the one used in the function signature. If you wanted to use the parameter <em>n</em> and not a new variable with the same name, you have to delimit the variable name with back-quote in the case definition, like this: <code>`n`</code></p>
<p><em>Here is a simple way to build you factorial function in Scala:</em></p>
<p><pre class="brush: scala;">
def fact(n) = (1 to n).foldLeft(1) { _ * _ }
</pre></p>
<h2>Pattern matching and collection: the look-alike approach</h2>
<p>Pattern matching may be applied to the collections. Below is a function that computes the length of a list without pattern matching:</p>
<p><pre class="brush: scala;">
def length[A](list : List[A]) : Int = {
    if (list.isEmpty) 0
    else 1 + length(list.tail)
  }
</pre></p>
<p>Here is the same function with pattern matching:</p>
<p><pre class="brush: scala;">
def length[A](list : List[A]) : Int = list match {
    case _ :: tail =&gt; 1 + length(tail)
    case Nil =&gt; 0
  }
</pre></p>
<p>In this function, there are two cases. The last one checks if the list is empty with the Nil value. The first one checks if there is at least one element is the list. The notation <code>_ :: tail</code> should be understood &#8220;a list with whatever head followed by a tail&#8221;. Here the tail can be <em>Nil</em> (ie. empty list) or a non-empty list.</p>
<p>To go further, we will use this approach with tuples in order to improve our method parserArgument() above:</p>
<p><pre class="brush: scala;">
  def parseArgument(arg : String, value: Any) = (arg, value) match {
    case (&quot;-l&quot;, lang) =&gt; setLanguageTo(lang)
    case (&quot;-o&quot; | &quot;--optim&quot;, n : Int) if ((0 &lt; n) &amp;&amp; (n &lt;= 5)) =&gt; setOptimizationLevelTo(n)
    case (&quot;-o&quot; | &quot;--optim&quot;, badLevel) =&gt; badOptimizationLevel(badLevel)
    case (&quot;-h&quot; | &quot;--help&quot;, null) =&gt; displayHelp()
    case bad =&gt; badArgument(bad)
  }
</pre></p>
<p>Notice first the use of the operator | that allows to match alternative forms of <em>arg</em> inside the tuple. Notice also the use of two patterns for options <code>-o</code> and <code>--optim</code>. These patterns are distinguished by the use of a guard condition. The guard conditions help you to get fine tuned pattern matching when pattern matching alone is not enough.</p>
<h2>Advanced pattern matching: case class</h2>
<p><strong>Case classes</strong> are classes with part of their behavior predefined in order to make easier their construction and their use in a pattern. Case classes enables you to manipulate parameterized symbols for example, parsed by a compiler or used by your internal Domain Specific Language (DSL).</p>
<p>The example below shows how to use case classes and pattern matching in order to build simple mathematical expressions, evaluate them, and compute their derivative. First, lets define the symbol to represent expressions: the variable X, constants, addition, multiplication, and the negative operator (for the fun!). Here <code>sealed</code> means that there is no other children of the class Expression outside of the namespace.</p>
<p><pre class="brush: scala;">
  sealed abstract class Expression
  case class X() extends Expression
  case class Const(value : Int) extends Expression
  case class Add(left : Expression, right : Expression) extends Expression
  case class Mult(left : Expression, right : Expression) extends Expression
  case class Neg(expr : Expression) extends Expression
</pre></p>
<p>Now, lets define a function to evaluate expressions with a given value for the variable by using pattern matching.</p>
<p><pre class="brush: scala;">
  def eval(expression : Expression, xValue : Int) : Int = expression match {
    case X() =&gt; xValue
    case Const(cst) =&gt; cst
    case Add(left, right) =&gt; eval(left, xValue) + eval(right, xValue)
    case Mult(left, right) =&gt; eval(left, xValue) * eval(right, xValue)
    case Neg(expr) =&gt; - eval(expr, xValue)
  }
</pre></p>
<p>Lets try the eval() function:</p>
<p><pre class="brush: scala;">
val expr = Add(Const(1), Mult(Const(2), Mult(X(), X())))  // 1 + 2 * X*X
assert(eval(expr, 3) == 19)
</pre></p>
<p>Now, we define a function that compute the (unreduced) derivative of an expression:</p>
<p><pre class="brush: scala;">
  def deriv(expression : Expression) : Expression = expression match {
    case X() =&gt; Const(1)
    case Const(_) =&gt; Const(0)
    case Add(left, right) =&gt; Add(deriv(left), deriv(right))
    case Mult(left, right) =&gt; Add(Mult(deriv(left), right), Mult(left, deriv(right)))
    case Neg(expr) =&gt; Neg(deriv(expr))
  }
</pre></p>
<p>Lets try the deriv() function:</p>
<p><pre class="brush: scala;">
val df = deriv(expr)
</pre></p>
<p>Here is what you get in <em>df</em>:</p>
<p><pre class="brush: scala;">
Add(Const(0),Add(Mult(Const(0),Mult(X(),X())),Mult(Const(2),Add(Mult(Const(1),X()),Mult(X(),Const(1))))))
// = 0 + (0 * X*X + 2 * (1*X + X*1)) = 4 * X
</pre></p>
<p><pre class="brush: scala;">
assert(eval(df, 3), 12)
</pre></p>
<h2>Other advanced pattern matching features</h2>
<p>There are some special notations used in the Scala&#8217;s pattern matching. Scala allows to put aliases on patterns or on parts of a pattern. The alias is put before the part of the pattern, separated by @. For example, in the expression <code>address @ Address(_, _, "Paris", "France")</code>, we want any addresses in Paris/France, but we do not care about its content after the match is done. So after, we just use the alias <em>address</em>.</p>
<p>There is also a specific notation to match sequences with _*. It matches zero, one or more elements in a sequence to its end.</p>
<p>In Scala, pattern matching does not appears only after a the function <code>match</code>. You can put pattern matching in any closure and also in a catch block.</p>
<p>You can provide your own behavior for pattern matching. This is called extractor. To do so, you have to provide your own implementation of the unapply() method (and/or unapplySeq() for a sequence).</p>
<h2>Conclusion</h2>
<p>In this post, we have seen different ways to use the pattern matching with Scala. The main advantage of such a feature is to provide an easy way to build alternative structures based the matching of scalar values, strings, collections, but also types and parameterized symbols. For me, pattern matching is one of the sexiest alternatives to if statements! A good use of pattern matching can make your program really readable and helps you to build an internal DSL.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kerflyn.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kerflyn.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kerflyn.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kerflyn.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kerflyn.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kerflyn.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kerflyn.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kerflyn.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kerflyn.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kerflyn.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kerflyn.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kerflyn.wordpress.com/159/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kerflyn.wordpress.com/159/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kerflyn.wordpress.com/159/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=159&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kerflyn.wordpress.com/2011/02/14/playing-with-scalas-pattern-matching/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa3d0249159281beafb1f149889c2dd4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kerflyn</media:title>
		</media:content>
	</item>
		<item>
		<title>[Report] A Trip In China 2010</title>
		<link>http://kerflyn.wordpress.com/2010/10/24/report-a-trip-in-china-2010/</link>
		<comments>http://kerflyn.wordpress.com/2010/10/24/report-a-trip-in-china-2010/#comments</comments>
		<pubDate>Sun, 24 Oct 2010 06:20:50 +0000</pubDate>
		<dc:creator>fsarradin</dc:creator>
				<category><![CDATA[MyLife]]></category>
		<category><![CDATA[China]]></category>
		<category><![CDATA[Guilin]]></category>
		<category><![CDATA[Shanghai]]></category>
		<category><![CDATA[ShanghaiExpo]]></category>

		<guid isPermaLink="false">http://kerflyn.wordpress.com/?p=224</guid>
		<description><![CDATA[Here is a report of my trip in China in October 2010. I speak about China, Shanghai, Guilin, Wuxi, Zhujiajiao, &#8230; and well, it also cover Expo 2010 in Shanghai. I haven&#8217;t used the services of travel agency, except for the trip in Guilin. For Guilin, I have used CITS, a Chinese travel agency. In this [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=224&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>Here is a report of my trip in China in October 2010. I speak about China, Shanghai, Guilin, Wuxi, Zhujiajiao, &#8230; and well, it also cover Expo 2010 in Shanghai. I haven&#8217;t used the services of travel agency, except for the trip in Guilin. For Guilin, I have used CITS, a Chinese travel agency.</em></p>
<p><em>In this report, I use a twitter style composed of &#8220;tweets&#8221; (small messages) with fake <span style="color:#0000ff;">#hashtag</span> <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  to highlight the topic. This style is more easy to use when you only have a smartphone to take notes. The tweets follow almost the chronological order.</em></p>
<p><em>Notice that some blocks of tweets are shifted to the right when it covers a more specific topic. Notice also that some of those tweets are in French, indicated by the tag [FR].</em></p>
<h2>The report</h2>
<p>Here I go for 2+1/2 weeks in <span style="color:#0000ff;">#China</span>. It&#8217;s the 3rd time.</p>
<p>Survival kit : <span style="color:#0000ff;">#python</span> and <span style="color:#0000ff;">#scheme</span> on my smartphone <span style="color:#0000ff;">#imageek</span></p>
<p>Have seen just a part of the Taihu lake from the plane <span style="color:#0000ff;">#china</span></p>
<p>I&#8217;ve just seen a giant thermometer on a blast furnace: <span style="color:#0000ff;">#Shanghai#Expo</span> 2010 ?</p>
<p>The last time, I&#8217;ve taken the maglev from Pudong airport to <span style="color:#0000ff;">#Shanghai</span></p>
<p>Maglev: Magnetic Levitation train, speed=400km/h, so cooool ! (thx Siemens) <span style="color:#0000ff;">#shanghai</span></p>
<p>Tested: there is no access to twitter from china</p>
<p>As tweeter isn&#8217;t accessible from china, I&#8217;ve noticed my tweets in my phone <span style="color:#0000ff;">#imanolife</span></p>
<p>For my tweets I have my smartphone and a small notepad</p>
<p>Tested: there is no google.cn. google.com is forward to google.com.hk (hong-kong) by default</p>
<p><span style="color:#0000ff;">#China</span>: world leader of &#8220;I fixed it&#8221; contest</p>
<p><span style="color:#0000ff;">#China</span> is a quarter of a day in advance compared to France. I&#8217;m fully awake at 2am :/</p>
<p>Octobre in <span style="color:#0000ff;">#Shanghai</span> is like the end of August in Paris</p>
<p>It&#8217;s all foggy in <span style="color:#0000ff;">#Shanghai</span> and around: pollution or natural?</p>
<h2 style="padding-left:30px;">Shanghai Sculpture Space</h2>
<p style="padding-left:30px;">At an art gallery at <span style="color:#0000ff;">#Shanghai</span> Sculpture Space in Red Town (<a href="http://www.sss570.com/">http://www.sss570.com/</a>)</p>
<div class="mceTemp" style="padding-left:30px;">
<dl class="wp-caption alignnone">
<dt class="wp-caption-dt"><a href="http://kerflyn.files.wordpress.com/2010/10/imag0176.jpg"><img class="size-medium wp-image-225" title="IMAG0176" src="http://kerflyn.files.wordpress.com/2010/10/imag0176.jpg?w=225&#038;h=300" alt="Suddenly, mini cooper, thousand of them" width="225" height="300" /></a></dt>
<dd class="wp-caption-dd">Suddenly, mini cooper, thousand of them</dd>
</dl>
</div>
<div class="mceTemp" style="padding-left:30px;">
<dl class="wp-caption alignnone">
<dt class="wp-caption-dt"><a href="http://kerflyn.files.wordpress.com/2010/10/imag0178.jpg"><img class="size-medium wp-image-226" title="IMAG0178" src="http://kerflyn.files.wordpress.com/2010/10/imag0178.jpg?w=300&#038;h=225" alt="Une voiture à 100 briques ?" width="300" height="225" /></a></dt>
<dd class="wp-caption-dd">[FR] Une voiture à 100 briques ?</dd>
</dl>
</div>
<div class="mceTemp" style="padding-left:30px;">
<dl class="wp-caption alignnone">
<dt class="wp-caption-dt"><a href="http://kerflyn.files.wordpress.com/2010/10/imag0180.jpg"><img class="size-medium wp-image-228" title="IMAG0180" src="http://kerflyn.files.wordpress.com/2010/10/imag0180.jpg?w=300&#038;h=225" alt="Chinese laptop: past meets present? future? or inside truth?" width="300" height="225" /></a></dt>
<dd class="wp-caption-dd">Chinese laptop: past meets present? future? or inside truth?</dd>
</dl>
</div>
<p>&#8220;1 people 1 dream&#8221; said CN olympic games <span style="color:#0000ff;">#china</span></p>
<p>&#8220;Be a better you&#8221; says Jiaotong University <span style="color:#0000ff;">#shanghai</span></p>
<p><span style="color:#0000ff;">#Shanghai#Expo</span> 2010: &#8220;Better City, Better Life&#8221;, and sometimes: &#8220;Deeper Freindship&#8221;</p>
<p>So cool! IT books worth only about 10 EUR&#8230; Even those in English from O&#8217;Really. And it seems to be legal <span style="color:#0000ff;">#imageek #china</span></p>
<p>Bah! A computer in <span style="color:#0000ff;">#Shanghai</span> has the same price than in Europe <img src='http://s0.wp.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<h2 style="padding-left:30px;">Wúxī (无锡) and Tài Hú Lake (太湖)</h2>
<p style="padding-left:30px;">10-08: today, I visit <span style="color:#0000ff;">#Wuxi</span> and <span style="color:#0000ff;">#Taihu</span> lake</p>
<p style="padding-left:30px;"><span style="color:#0000ff;">#Taihu</span> lake: huge lake close to Shanghai: 2h by bus. It&#8217;s like a sea without waves</p>
<p style="padding-left:30px;"><span style="color:#0000ff;">#Taihu</span> lake: an average deep of 2m for more than 2000km² (see <a href="http://en.wikipedia.org/wiki/Taihu_Lake">http://en.wikipedia.org/wiki/Taihu_Lake</a>)</p>
<div class="mceTemp" style="padding-left:30px;">
<dl class="wp-caption alignnone">
<dt class="wp-caption-dt"><a href="http://kerflyn.files.wordpress.com/2010/10/img_3369.jpg"><img class="size-medium wp-image-229" title="IMG_3369" src="http://kerflyn.files.wordpress.com/2010/10/img_3369.jpg?w=300&#038;h=225" alt="A tree at the top of a building #wuxi" width="300" height="225" /></a></dt>
<dd class="wp-caption-dd">A tree at the top of a building <span style="color:#0000ff;">#wuxi</span></dd>
</dl>
</div>
<div class="mceTemp" style="padding-left:30px;">
<dl class="wp-caption alignnone">
<dt class="wp-caption-dt"><a href="http://kerflyn.files.wordpress.com/2010/10/junks.jpg"><img class="size-full wp-image-246" title="junks" src="http://kerflyn.files.wordpress.com/2010/10/junks.jpg?w=700&#038;h=225" alt="Some junks on the #Taihu lake. They are rented by the government for the Chinese National Day" width="700" height="225" /></a></dt>
<dd class="wp-caption-dd">Some junks on the <span style="color:#0000ff;">#Taihu</span> lake. They are rented by the government for the Chinese National Day</dd>
</dl>
</div>
<p style="padding-left:30px;"><a href="http://kerflyn.files.wordpress.com/2010/10/img_3424.jpg"><img class="alignnone size-medium wp-image-247" title="IMG_3424" src="http://kerflyn.files.wordpress.com/2010/10/img_3424.jpg?w=300&#038;h=225" alt="" width="300" height="225" /></a></p>
<p style="padding-left:30px;">Poor <span style="color:#0000ff;">#Taihu </span>lake: a green alga on its surface gives the impression that someone has poured some paint</p>
<p>Auchan Carrefour Citroën Peugeot Ikea Mercedes Lamborghini etc.: am I in <span style="color:#0000ff;">#China</span>?</p>
<p><span style="color:#0000ff;">#China</span> is one of the only country where you can see cars from all around the world</p>
<p>Chinese people are musicians: they like to play with the horn of their car <span style="color:#0000ff;">#IWantToSleep#china</span></p>
<p><span style="color:#0000ff;">#Shanghai</span> at night is outstanding: the buildings are covered with thousand of dancing lights</p>
<p>There&#8217;s even a building that displays a giant TV screen on its front <span style="color:#0000ff;">#imahick #shanghai</span></p>
<p>The top of some buildings have a specific decoration: a crown, a palace entrance, an observatory, etc. <span style="color:#0000ff;">#shanghai</span></p>
<div id="attachment_248" class="wp-caption alignnone" style="width: 310px"><a href="http://kerflyn.files.wordpress.com/2010/10/img_4617.jpg"><img class="size-medium wp-image-248" title="IMG_4617" src="http://kerflyn.files.wordpress.com/2010/10/img_4617.jpg?w=300&#038;h=225" alt="There's a building top that looks like a golden mansion #shanghai" width="300" height="225" /></a><p class="wp-caption-text">There&#039;s a building top that looks like a golden mansion #shanghai</p></div>
<p>[FR] En <span style="color:#0000ff;">#Chine</span>, pas d&#8217;hypocrisie : on peut vraiment voir les fonctionnaires dormir à leur guichet <em>lol</em></p>
<p>Bah! 17h and the night is falling already <span style="color:#0000ff;">#shanghai</span></p>
<p>Liked: there&#8217;s a countdown for each traffic light, for cars, for pedestrians, for the red light and the green light <span style="color:#0000ff;">#china</span></p>
<p>Good idea: on most of the street name signs, names are written in Chinese and in Pinyin/English <span style="color:#0000ff;">#china</span></p>
<p>Good idea: on the street name sign, you know if you are on the east/west/north/south/middle side of the street and you know where are the other sides <span style="color:#0000ff;">#china</span></p>
<p>Commerce is everywhere you can put an eye on. But concurrency is very hard <span style="color:#0000ff;">#china</span></p>
<p>Today is 10-10-10&#8230; Binary for 42. OMG! what does means? <span style="color:#0000ff;">#imageek</span></p>
<p>Today is 10-10-10&#8230; Doesn&#8217;t mean anything for <span style="color:#0000ff;">#China</span> :/</p>
<h2 style="padding-left:30px;">Zhūjiājiǎo (朱家角)</h2>
<p style="padding-left:30px;">10-10: today, I visit <span style="color:#0000ff;">#ZhuJiaJiao #china</span></p>
<p style="padding-left:30px;">There are very nice small villages (eg. <span style="color:#0000ff;">#ZhuJiaJiao</span>) with water channels like in Venice <span style="color:#0000ff;">#shanghai</span></p>
<p style="padding-left:60px;"><span style="color:#0000ff;"> </span></p>
<div class="mceTemp" style="padding-left:30px;">
<dl class="wp-caption alignnone">
<dt class="wp-caption-dt"><a href="http://kerflyn.files.wordpress.com/2010/10/img_3626.jpg"><img class="size-medium wp-image-249" title="IMG_3626" src="http://kerflyn.files.wordpress.com/2010/10/img_3626.jpg?w=300&#038;h=225" alt="Doesn't it look like Venice? #ZhuJiaJiao" width="300" height="225" /></a></dt>
<dd class="wp-caption-dd">Doesn&#8217;t it look like Venice? <span style="color:#0000ff;">#ZhuJiaJiao</span></dd>
</dl>
</div>
<p style="padding-left:30px;"><span style="color:#0000ff;">#ZhuJiaJiao</span> is a city close to Shanghai: 1h by bus</p>
<p style="padding-left:30px;">If you don&#8217;t like touristic cities full of commerces like Mont-Saint-Michel, don&#8217;t come at <span style="color:#0000ff;">#ZhuJiaJiao</span></p>
<p style="padding-left:30px;">There is a smell in the air of a mix of a sweet and/or fatty steamed foods <span style="color:#0000ff;">#ZhuJiaJiao</span></p>
<h2 style="padding-left:30px;">Shanghai places and history</h2>
<p style="padding-left:30px;">Some places in <span style="color:#0000ff;">#Shanghai</span>: The Bund, NanJing lu and People Square, HuaiHai lu, XuJiaHui, PuDong</p>
<p style="padding-left:30px;"><span style="color:#0000ff;">#Shanghai</span> is word with two syllables, so 2 Chinese characters: <em>shang</em> (上) = on, <em>hai</em> (海)= the sea</p>
<p style="padding-left:30px;"><span style="color:#0000ff;">#Shanghai</span> is mainly divided in 2 parts by the HuangPu river</p>
<p style="padding-left:30px;"><span style="color:#0000ff;">#Shanghai</span> was originally a village of fishers</p>
<p style="padding-left:30px;">During the 19th century, the main foreign countries has settled their concession around the Bund (west side of the HuangPu) <span style="color:#0000ff;">#shanghai</span></p>
<p style="padding-left:30px;">Located in the south part of the city, the French concession has grown to the west <span style="color:#0000ff;">#shanghai</span></p>
<p style="padding-left:30px;">We can find <em>HuaiHai lu</em> that was originally called <em>Avenue Joffre</em> <span style="color:#0000ff;">#shanghai</span></p>
<p><span style="color:#0000ff;">#Shanghai</span> is one of the most European cities in China. Here, I feel somewhat at home, compared to Beijing</p>
<p>Or is it the most New-Yorker of the European cities? <span style="color:#0000ff;">#shanghai</span></p>
<h2 style="padding-left:30px;">Guìlín (桂林)</h2>
<p style="padding-left:30px;">10-11: today I go to <span style="color:#0000ff;">#Guilin</span> for 3 days. It is full of beautiful landscape. 2h from Shanghai by plane</p>
<p style="padding-left:30px;"><span style="color:#0000ff;">#Guilin</span> is located in the Guangxi Zhuang region in the south of China (<a href="http://en.wikipedia.org/wiki/Guilin">http://en.wikipedia.org/wiki/Guilin</a>)</p>
<p style="padding-left:30px;">Going to test a domestic flight with <a href="http://www.juneyaoairlines.com/">Juneyao Airlines</a> to go to <span style="color:#0000ff;">#Guilin</span></p>
<p style="padding-left:30px;">OH! Changing the boarding gate two times, plane is late due to air flow (1h). WTF! <span style="color:#0000ff;">#china</span></p>
<p style="padding-left:30px;">Inside the plane at last! Seems to be a small airbus (A320). The inside is nice <span style="color:#0000ff;">#china</span></p>
<p style="padding-left:30px;">[FR] La nourriture à bord est acceptable pour une bouche française. <span style="color:#0000ff;">#chine</span></p>
<p style="padding-left:30px;">[FR] &#8221;Mini french bread&#8221; est une hérésie: ici, c&#8217;est un pain au lait assez sucré <span style="color:#0000ff;">#chine</span></p>
<p style="padding-left:30px;">Tested: green clementine &#8211; it&#8217;s good and it leaves virtually no smell on your fingers <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  <span style="color:#0000ff;">#china</span></p>
<p style="padding-left:30px;">Has landed. The atmosphere is full of humidity <span style="color:#0000ff;">#guilin</span></p>
<p style="padding-left:30px;">even bikes can drive on motorway! <span style="color:#0000ff;">#guilin</span></p>
<div class="mceTemp" style="padding-left:30px;">
<dl class="wp-caption alignnone">
<dt class="wp-caption-dt"><a href="http://kerflyn.files.wordpress.com/2010/10/img_3749.jpg"><img class="size-medium wp-image-252" title="IMG_3749" src="http://kerflyn.files.wordpress.com/2010/10/img_3749.jpg?w=300&#038;h=225" alt="#Guilin landscape" width="300" height="225" /></a></dt>
<dd class="wp-caption-dd"><span style="color:#0000ff;">#Guilin</span> landscape</dd>
</dl>
</div>
<p style="padding-left:30px;">people are poor. &#8220;There is nothing except tourism and past. <span style="color:#0000ff;">#Guilin</span> is like a beautiful woman with dirty clothes&#8221; said the guide</p>
<p style="padding-left:30px;"><span style="color:#0000ff;">#Guilin</span> landscape appears on 20 yuan bills, it also appears in Star Wars and Doom video game</p>
<p style="padding-left:30px;">Visiting by boat on the Li river (Li jiang in Chinese). Destination: Yangshou (<a href="http://wikitravel.org/en/Yangshuo">http://wikitravel.org/en/Yangshuo</a>). <span style="color:#0000ff;">#Guilin</span> landscape is really beautiful!</p>
<p style="padding-left:30px;">Li river: the water is almost clear and absolutly not deep <span style="color:#0000ff;">#guilin</span></p>
<p style="padding-left:30px;">there&#8217;s a mountain with 9 horses naturally inscribed on. You can also see faces. Chinese people have a very strong imagination <span style="color:#0000ff;">#guilin</span></p>
<div class="mceTemp" style="padding-left:30px;">
<dl class="wp-caption alignnone">
<dt class="wp-caption-dt"><a href="http://kerflyn.files.wordpress.com/2010/10/img_3702.jpg"><img class="size-medium wp-image-253 " title="IMG_3702" src="http://kerflyn.files.wordpress.com/2010/10/img_3702.jpg?w=225&#038;h=300" alt="A bamboo raft on the Li river#guilin" width="225" height="300" /></a></dt>
<dd class="wp-caption-dd">A bamboo raft on the Li river <span style="color:#0000ff;">#guilin</span></dd>
</dl>
</div>
<p style="padding-left:30px;">now on board of a sort of raft made of 10 bamboo sticks. Never been so closed from water on a boat. <span style="color:#0000ff;">#guilin</span></p>
<p style="padding-left:30px;">the water of the river is good, I would like to swin <span style="color:#0000ff;">#guilin</span></p>
<p style="padding-left:30px;">The river is 6m deep max <span style="color:#0000ff;">#guilin</span></p>
<p style="padding-left:30px;">Result: have crossed some small waterfalls and my bottom is a little wet &#8211; nice <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  for the rest, it&#8217;s almost quiet <span style="color:#0000ff;">#guilin</span></p>
<p style="padding-left:30px;"><span style="color:#0000ff;">#Guilin</span> altitude: about 200m</p>
<p style="padding-left:30px;">Yangshou: has seen an entertainment named &#8220;Impression Liu Sanjie&#8221;. Made by the famous Chinese movie director Zhang Yimou. Actors come from local villages. It was really beautiful <span style="color:#0000ff;">#guilin</span></p>
<div class="mceTemp" style="padding-left:30px;">
<dl class="wp-caption alignnone">
<dt class="wp-caption-dt"><a href="http://kerflyn.files.wordpress.com/2010/10/img_3936.jpg"><img class="size-medium wp-image-254" title="IMG_3936" src="http://kerflyn.files.wordpress.com/2010/10/img_3936.jpg?w=300&#038;h=225" alt="Impression Liu Sanjie: a woman dancing on the moon #guilin" width="300" height="225" /></a></dt>
<dd class="wp-caption-dd">Impression Liu Sanjie: a woman dancing on the moon <span style="color:#0000ff;">#guilin</span></dd>
</dl>
</div>
<p style="padding-left:30px;">Yangshou: an American asked where I come from. I needed time not to answer &#8220;faguo&#8221; (法国)</p>
<p style="padding-left:30px;">Yangshou: There&#8217;s a street with a heavy crowd at night. It&#8217;s full of night bars with some individuals that dances in front <span style="color:#0000ff;">#guilin</span></p>
<p style="padding-left:30px;">[FR] En France, 13 = malheur. En <span style="color:#0000ff;">#Chine</span>, 13 ne veut rien dire. Par contre, 8 = bonheur, 4 = mort/serpent/malheur</p>
<p style="padding-left:30px;">The small safe in the hotel is not sealed. It is lightweight and can be put in a large suitcase. Seriously WTF? <span style="color:#0000ff;">#china</span></p>
<p style="padding-left:30px;">Chinese ancient imperial examination system has 7 levels <span style="color:#0000ff;">#china</span></p>
<p style="padding-left:30px;">Have to pass an exam. 2&#8242; to write the answers in Chinese with an old Chinese pencil. It&#8217;s really hard to write &#8220;I don&#8217;t know&#8221;! <span style="color:#0000ff;">#guilin#china</span></p>
<p style="padding-left:30px;">Chinese exam: every student is behind a desk in a small cell. Students can&#8217;t cheat on each other <span style="color:#0000ff;">#guilin#china</span></p>
<p style="padding-left:30px;">Have to go in a Japanese restaurant to drink a safe beer (Asahi). The food in the restaurant is really good and different compared the Japanese restaurant in France <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  <span style="color:#0000ff;">#guilin</span></p>
<p style="padding-left:30px;"><span style="color:#0000ff;">#China</span> really miss something important: cheese :p</p>
<p style="padding-left:30px;">taken in photos with 3 women from Shanghai wearing traditional clothes of <span style="color:#0000ff;">#Guilin</span> <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p style="padding-left:30px;">have drunken some beer from <span style="color:#0000ff;">#Guilin</span>. It&#8217;s water with a taste of beer :/ QsingTao is better</p>
<p style="padding-left:30px;"><em>/me</em> made some adv. about France: good wines, perfums and cheeses <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  <span style="color:#0000ff;">#FTW #guilin</span></p>
<p style="padding-left:30px;">end of trip in <span style="color:#0000ff;">#Guilin</span>. Good journey. Forgot everything about my French life except my language</p>
<p style="padding-left:30px;">plane from Guilin to Shanghai is one hour late too, due to air traffic congestion <img src='http://s0.wp.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  <span style="color:#0000ff;">#china</span></p>
<p><span style="color:#0000ff;">#Shanghai</span> at 3am is unrecognizable: the buildings have disappeared in the dark. The taxis have invaded the streets.  They lookout for the lost costumer</p>
<p>The taxis wait the customers even at the bus stop or at the restaurant exit <span style="color:#0000ff;">#shanghai</span></p>
<p>My little Chinese guidebook confuses men&#8217;s/ladies&#8217; restroom (to know the difference can save your life!)</p>
<p>It&#8217;s possible to hear some repeated explosions of firecrackers to wish happiness. This leaves some traces of red paper in the street <span style="color:#0000ff;">#china</span></p>
<h2 style="padding-left:30px;">Shanghai Expo 2010 (中国2010年上海世界博览会)</h2>
<p style="padding-left:30px;">Inside <span style="color:#0000ff;">#Shanghai#Expo</span> 2010 for one day</p>
<p style="padding-left:30px;">Space Home Pavilion: nothing to do here <span style="color:#0000ff;">#shanghai#expo</span></p>
<p style="padding-left:30px;">Some interesting sculptures a the Shanghai shipyard pavilion <span style="color:#0000ff;">#shanghai#expo</span></p>
<div class="mceTemp" style="padding-left:30px;">
<dl class="wp-caption alignnone">
<dt class="wp-caption-dt"><a href="http://kerflyn.files.wordpress.com/2010/10/img_4289.jpg"><img class="size-medium wp-image-245" title="IMG_4289" src="http://kerflyn.files.wordpress.com/2010/10/img_4289.jpg?w=300&#038;h=225" alt="Pavilion of Future: a giant thermometer on a blast furnace displays 24°C #shanghai#expo" width="300" height="225" /></a></dt>
<dd class="wp-caption-dd">Pavilion of Future: a giant thermometer on a blast furnace displays 24°C <span style="color:#0000ff;">#shanghai#expo</span></dd>
</dl>
</div>
<p style="padding-left:30px;">Pavilion of Future: giant books, light games, playing with senses&#8230; imagine the cities of tomorrow: exiting <span style="color:#0000ff;">#shanghai#expo</span></p>
<div class="mceTemp" style="padding-left:30px;">
<dl class="wp-caption alignnone">
<dt class="wp-caption-dt"><a href="http://kerflyn.files.wordpress.com/2010/10/img_4302.jpg"><img class="size-medium wp-image-255" title="IMG_4302" src="http://kerflyn.files.wordpress.com/2010/10/img_4302.jpg?w=300&#038;h=225" alt="Future Pavilion: enregy city #shanghai#expo" width="300" height="225" /></a></dt>
<dd class="wp-caption-dd">Future Pavilion: enregy city <span style="color:#0000ff;">#shanghai#expo</span></dd>
</dl>
</div>
<p style="padding-left:30px;">have to cross the river. Too many people waiting for the ferry or the bus <span style="color:#0000ff;">#shanghai#expo</span></p>
<p style="padding-left:30px;">Know what? The pavilions of North Korea and of Iran are neighbours <span style="color:#0000ff;">#shanghai#expo</span></p>
<p style="padding-left:30px;">France Pavilion: Chinese faces, metalic roses on water, nice looking Citroën berlin car, vertical green elements <span style="color:#0000ff;">#shanghai#expo</span></p>
<div class="mceTemp" style="padding-left:30px;">
<dl class="wp-caption alignnone">
<dt class="wp-caption-dt"><a href="http://kerflyn.files.wordpress.com/2010/10/img_4326.jpg"><img class="size-medium wp-image-256" title="IMG_4326" src="http://kerflyn.files.wordpress.com/2010/10/img_4326.jpg?w=300&#038;h=225" alt="France Pavilion: nice looking Citroën berlin car #shanghai#expo" width="300" height="225" /></a></dt>
<dd class="wp-caption-dd">France Pavilion: nice looking Citroën berlin car <span style="color:#0000ff;">#shanghai#expo</span></dd>
</dl>
</div>
<p style="padding-left:30px;">France Pavilion: has seen Léon, our French mascot <span style="color:#0000ff;">#shanghai#expo</span></p>
<p style="padding-left:30px;">France Pavilion: &#8220;la ville sensuelle&#8221;, romantism with lounge music, time to time: Eiffel tower <span style="color:#0000ff;">#shanghai#expo</span></p>
<p style="padding-left:30px;">France Pavilion: I&#8217;ve the feeling that this was an expo about Paris <span style="color:#0000ff;">#shanghai#expo</span></p>
<p style="padding-left:30px;">Belgian fries (at Léon de Bruxelles) and waffles sold next to the Belgian/EU pavillon (no beer?) <span style="color:#0000ff;">#shanghai#expo</span></p>
<p style="padding-left:30px;">Spain Pavilion: this one is really sensual with those women dancing flamengo! <span style="color:#0000ff;">#shanghai#expo</span></p>
<p style="padding-left:30px;">Spain Pavilion: Picasso, horses that cross a room: yes! <span style="color:#0000ff;">#shanghai#expo</span></p>
<p style="padding-left:30px;">Spain Pavilion: babies on curtains: nice! Giant baby at the end: o_O <span style="color:#0000ff;">#shanghai#expo</span></p>
<p style="padding-left:30px;">UK Pavilion: only the transparent structure is interesting <span style="color:#0000ff;">#shanghai#expo</span></p>
<p style="padding-left:30px;">Italy Pavilion: really like this one. Full of good surprises <span style="color:#0000ff;">#shanghai#expo</span></p>
<p style="padding-left:30px;">Italy Pavilion: Ferrari, pasta, wine, many kind of art <span style="color:#0000ff;">#shanghai#expo</span></p>
<div class="mceTemp" style="padding-left:30px;">
<dl class="wp-caption alignnone">
<dt class="wp-caption-dt"><a href="http://kerflyn.files.wordpress.com/2010/10/img_4412.jpg"><img class="size-medium wp-image-257" title="IMG_4412" src="http://kerflyn.files.wordpress.com/2010/10/img_4412.jpg?w=300&#038;h=225" alt="Italy Pavilion: an upside down room #shanghai#expo" width="300" height="225" /></a></dt>
<dd class="wp-caption-dd">Italy Pavilion: an upside down room <span style="color:#0000ff;">#shanghai#expo</span></dd>
</dl>
</div>
<p style="padding-left:30px;">Italy Pavilion: Italy, you have to remember that the ground floor is numbered 1 in China, not 0 <span style="color:#0000ff;">#shanghai#expo</span></p>
<p style="padding-left:30px;">Luxembourg Pavilion: not so good <span style="color:#0000ff;">#shanghai#expo</span></p>
<p style="padding-left:30px;">Would like to visit those pavilion: Algeria, Peru, China, China&#8217;s Petroleum <span style="color:#0000ff;">#shanghai#expo</span></p>
<p>[FR] Il est vendu en <span style="color:#0000ff;">#Chine</span> des modèles de Peugeot 307 et 408 et de Citroën qu&#8217;on ne verra jamais en France</p>
<p>[FR] La Peugeot 206 n&#8217;a pas changé en dehors d&#8217;une inscription en chinois <span style="color:#0000ff;">#chine</span></p>
<p>In <span style="color:#0000ff;">#China</span>, superstitions have also a long life</p>
<p>24°C in <span style="color:#0000ff;">#Shanghai</span>. The air is muggy</p>
<p>Jewelry made of jade is very popular <span style="color:#0000ff;">#china</span></p>
<p>Wrong good idea: switch on the light in the hallway by hitting the floor with your foot <span style="color:#0000ff;">#IWantToSleep #china</span></p>
<p>In <span style="color:#0000ff;">#China</span>, you don&#8217;t eat a yoghurt, you drink it&#8230; through a straw!</p>
<p>[FR] Viens de voir la photo de la famille présidentielle sur fond du pavillon français dans petit journal shanghaien <span style="color:#0000ff;">#shanghai#expo</span></p>
<p>[FR] Carla y montre la mascotte française : Léon, un petit chat aux couleurs française <span style="color:#0000ff;">#shanghai#expo</span></p>
<h2 style="padding-left:30px;">The Dream in the Red Chamber (<em>Hóng Lóu Mèng</em> - 红楼梦)</h2>
<p style="padding-left:30px;">Grand View Garden (<em>Dàguānyuán</em> &#8211; 大观园) is a touristic place with a garden, a mansion, and a pagoda on a island. It&#8217;s a little frequent: it&#8217;s nice <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p style="padding-left:30px;"><span style="color:#0000ff;">#Daguanyuan</span> represents the place where the story of &#8220;The Dream in the Red Chamber&#8221; (<em>Le Rêve dans le Pavillon Rouge</em> in French) would have held</p>
<div class="mceTemp" style="padding-left:30px;">
<dl class="wp-caption alignnone">
<dt class="wp-caption-dt"><a href="http://kerflyn.files.wordpress.com/2010/10/img_4516.jpg"><img class="size-medium wp-image-258" title="IMG_4516" src="http://kerflyn.files.wordpress.com/2010/10/img_4516.jpg?w=300&#038;h=225" alt="The throne room #daguanyuan" width="300" height="225" /></a></dt>
<dd class="wp-caption-dd">The throne room <span style="color:#0000ff;">#daguanyuan</span></dd>
</dl>
</div>
<p style="padding-left:30px;">&#8220;The Dream in the Red Chamber&#8221; is one the four important novels in the Chinese literature</p>
<p style="padding-left:30px;"><span style="color:#0000ff;">#Daguanyuan</span> is a place that is often used as a movie set. Each movie is an opportunity to restore the mansion</p>
<div id="attachment_244" class="wp-caption alignnone" style="width: 710px"><a href="http://kerflyn.files.wordpress.com/2010/10/chinese-portal.jpg"><img class="size-full wp-image-244" title="Chinese-portal" src="http://kerflyn.files.wordpress.com/2010/10/chinese-portal.jpg?w=700&#038;h=229" alt="Many portals for building entrances in #China are folding, mounted on wheels and automated" width="700" height="229" /></a><p class="wp-caption-text">Many portals for building entrances in #China are folding, mounted on wheels and automated</p></div>
<p>Seen: Asian people in Tibetan dresses, dancing on a Tibetan music in front of a Tibetan restaurant <span style="color:#0000ff;">#shanghai</span></p>
<h2 style="padding-left:30px;">Restaurant in China</h2>
<p style="padding-left:30px;">The chic restaurant is located in a tower. You can ask for a private lounge (there a many) <span style="color:#0000ff;">#china</span></p>
<p style="padding-left:30px;">In a Chinese restaurant, you usually find a large round table with a lazy Susan made of glass <span style="color:#0000ff;">#china</span></p>
<p style="padding-left:30px;">Dishes arrive with the same rhythm. They are put on the lazy Susan. Everyone around the table helps oneself as he wants <span style="color:#0000ff;">#china</span></p>
<p style="padding-left:30px;">A pair of chopsticks, a spoon made of porcelain, a bowl for the rice and the soup, a bowl for the tea, a small plate: here are your weapons to eat in <span style="color:#0000ff;">#China</span></p>
<p style="padding-left:30px;">Just notice that <em>china</em> with a small &#8216;c&#8217; means porcelain in English!</p>
<p>Seen: someone has dropped (not done on purpose) a bottle in a gutter. 5min later, an old man on a bike collected it in a view to sell it <span style="color:#0000ff;">#shanghai</span></p>
<p>There&#8217;s no need for a street cleaning company, because poor people work on them already <span style="color:#0000ff;">#shanghai</span></p>
<p>Bah! Spitting is a common practice <span style="color:#0000ff;">#china</span></p>
<p>Have to back soon: it&#8217;s forecast 22°C in <span style="color:#0000ff;">#Shanghai</span>. In Paris, 7°C with a strike maybe <img src='http://s0.wp.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  Why should I come back?</p>
<p>I spent 2 weeks and a half in October wearing t-shirts and sunglasses <span style="color:#0000ff;">#notashamed</span></p>
<p>I really forgot lots of thing about my French life. That&#8217;s what I call a good trip <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kerflyn.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kerflyn.wordpress.com/224/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kerflyn.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kerflyn.wordpress.com/224/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kerflyn.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kerflyn.wordpress.com/224/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kerflyn.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kerflyn.wordpress.com/224/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kerflyn.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kerflyn.wordpress.com/224/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kerflyn.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kerflyn.wordpress.com/224/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kerflyn.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kerflyn.wordpress.com/224/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=224&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kerflyn.wordpress.com/2010/10/24/report-a-trip-in-china-2010/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa3d0249159281beafb1f149889c2dd4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kerflyn</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2010/10/imag0176.jpg?w=225" medium="image">
			<media:title type="html">IMAG0176</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2010/10/imag0178.jpg?w=300" medium="image">
			<media:title type="html">IMAG0178</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2010/10/imag0180.jpg?w=300" medium="image">
			<media:title type="html">IMAG0180</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2010/10/img_3369.jpg?w=300" medium="image">
			<media:title type="html">IMG_3369</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2010/10/junks.jpg" medium="image">
			<media:title type="html">junks</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2010/10/img_3424.jpg?w=300" medium="image">
			<media:title type="html">IMG_3424</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2010/10/img_4617.jpg?w=300" medium="image">
			<media:title type="html">IMG_4617</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2010/10/img_3626.jpg?w=300" medium="image">
			<media:title type="html">IMG_3626</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2010/10/img_3749.jpg?w=300" medium="image">
			<media:title type="html">IMG_3749</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2010/10/img_3702.jpg?w=225" medium="image">
			<media:title type="html">IMG_3702</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2010/10/img_3936.jpg?w=300" medium="image">
			<media:title type="html">IMG_3936</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2010/10/img_4289.jpg?w=300" medium="image">
			<media:title type="html">IMG_4289</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2010/10/img_4302.jpg?w=300" medium="image">
			<media:title type="html">IMG_4302</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2010/10/img_4326.jpg?w=300" medium="image">
			<media:title type="html">IMG_4326</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2010/10/img_4412.jpg?w=300" medium="image">
			<media:title type="html">IMG_4412</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2010/10/img_4516.jpg?w=300" medium="image">
			<media:title type="html">IMG_4516</media:title>
		</media:content>

		<media:content url="http://kerflyn.files.wordpress.com/2010/10/chinese-portal.jpg" medium="image">
			<media:title type="html">Chinese-portal</media:title>
		</media:content>
	</item>
		<item>
		<title>[FAQ] Learn To Program In Python</title>
		<link>http://kerflyn.wordpress.com/2010/09/26/faq-learn-to-program-in-python/</link>
		<comments>http://kerflyn.wordpress.com/2010/09/26/faq-learn-to-program-in-python/#comments</comments>
		<pubDate>Sun, 26 Sep 2010 14:06:26 +0000</pubDate>
		<dc:creator>fsarradin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[faq]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://kerflyn.wordpress.com/?p=200</guid>
		<description><![CDATA[Here is a small FAQ about how to become a programmer in Python and making progress. Do not expect this FAQ to be completely logical. Python&#8217;s name comes from Monty Python&#8217;s Flying Circus. So you have to experience the language to appreciate it&#8230; before to think ;p Python is simple, so becoming a Python programmer [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=200&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Here is a small FAQ about how to become a programmer in Python and making progress. Do not expect this FAQ to be completely logical. Python&#8217;s name comes from <a href="http://en.wikipedia.org/wiki/Monty_Python's_Flying_Circus">Monty Python&#8217;s Flying Circus</a>. So you have to experience the language to appreciate it&#8230; before to think ;p</p>
<p>Python is simple, so becoming a Python programmer is simple too!</p>
<h2>How to learn to program in Python?</h2>
<p>The answer is simple! Go to the address <a href="http://www.python.org/doc/">http://www.python.org/doc/</a> and click on the Tutorial link.</p>
<p>Once you have done with the tutorial, you will not be a strong Python programmer. In fact, at the end, you will be able to put most of your ideas into a Python script. It helps if you have experienced programming with another language and if you have some knowledge in object-oriented programming (OOP) &#8212; the last is optional. But, above all, it is necessary to have a sufficient open mind.</p>
<h2>How to be a better Python programmer?</h2>
<p>The answer is simple! Practice Python and read the source code of the files in the Python standard library ($PYTHONPATH/Lib).</p>
<p>Do not fear that kind of code, it will not bite you! By doing this, you will learn some patterns and some idioms used in Python. The bulk of the source code in the standard library is sufficiently clear.</p>
<h2>How to become a strong Python programmer?</h2>
<p>The answer is simple! Read the PEPs (Python Enhancement Proposals) starting from this one <a href="http://www.python.org/dev/peps/">http://www.python.org/dev/peps/</a> and use google.</p>
<p>Here the goal is to explore what is unknown by most of the programmer or by other language. Do you know what is a generator or a decorator? Can the list comprehension make my life as a developer better? And what about the database API? The answers are in the PEPs and google.</p>
<p>For example, to learn more about Python&#8217;s decorators, take a look at <a href="http://www.python.org/dev/peps/pep-0318/">http://www.python.org/dev/peps/pep-0318/</a>.</p>
<h2>Is this enough?</h2>
<p>The answer is simple! <strong>Absolutely not!</strong></p>
<p>All the answers here should be considered as starting points. After that, there are many things to explore. But, you have to do the same thing you would do with another language to improve your skill: explore forums, listen to conferences, answer to questions, and contribute.</p>
<h2><em>To Infinity And Beyond</em></h2>
<pre><span style="color:#800000;">$ python -c "import this"</span>
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kerflyn.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kerflyn.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kerflyn.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kerflyn.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kerflyn.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kerflyn.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kerflyn.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kerflyn.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kerflyn.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kerflyn.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kerflyn.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kerflyn.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kerflyn.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kerflyn.wordpress.com/200/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kerflyn.wordpress.com&amp;blog=13785574&amp;post=200&amp;subd=kerflyn&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kerflyn.wordpress.com/2010/09/26/faq-learn-to-program-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/fa3d0249159281beafb1f149889c2dd4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kerflyn</media:title>
		</media:content>
	</item>
	</channel>
</rss>
