<?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>brain driven development</title>
	<atom:link href="http://gleichmann.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://gleichmann.wordpress.com</link>
	<description>a development driven blog</description>
	<lastBuildDate>Tue, 17 Jan 2012 21:10:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='gleichmann.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>brain driven development</title>
		<link>http://gleichmann.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://gleichmann.wordpress.com/osd.xml" title="brain driven development" />
	<atom:link rel='hub' href='http://gleichmann.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Functional Scala: Curried Functions and spicy Methods</title>
		<link>http://gleichmann.wordpress.com/2011/12/04/functional-scala-curried-functions-and-spicy-methods/</link>
		<comments>http://gleichmann.wordpress.com/2011/12/04/functional-scala-curried-functions-and-spicy-methods/#comments</comments>
		<pubDate>Sun, 04 Dec 2011 16:06:39 +0000</pubDate>
		<dc:creator>Mario Gleichmann</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[Curried Functions]]></category>
		<category><![CDATA[Currying]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://gleichmann.wordpress.com/?p=838</guid>
		<description><![CDATA[Welcome back to another episode of functional Scala! As said some time before, we&#8217;ve by far not reached the end when it comes to all those basic concepts of functional programming. One of the most powerful ideas we&#8217;ve discovered so far, was that of so called higher order functions. Since functions can be treated as [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=838&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Welcome back to another episode of functional Scala!</p>
<p>As said some time before, we&#8217;ve by far not reached the end when it comes to all those basic concepts of functional programming. One of the most powerful ideas we&#8217;ve discovered so far, was that of so called<a title="Higher Order Functions" href="http://gleichmann.wordpress.com/2010/11/28/high-higher-higher-order-functions/" target="_blank"> higher order functions</a>. Since functions can be treated as values (like Numbers or Strings), we can pass them as ordinary arguments to some other functions. You may remember our function <em>filter</em>, which not only takes a list of elements to be filtered, but also a function (a so called predicate function, resulting into a boolean value) which decides for every list element to be in the filtered list or not.</p>
<p>In this episode, we&#8217;ll see that we&#8217;re not only restricted to accept another function as an argument but could also come up with some sensible functions which may return another function as their result. Again, this is nothing special if you look at a function as an ordinary value which can be passed around like any other value of any other type. While on that road, we&#8217;ll naturally discover how that idea is closely related to what&#8217;s called <em>function currying</em>. So hold on, you&#8217;ll see what&#8217;s that all about in the next minutes &#8230;</p>
<h2>Game of sight</h2>
<p>Let&#8217;s pretend we wanna write a &#8216;Game of sight&#8217;. Within that game, it&#8217;s critical to detect if a certain object is within a certain area so that it&#8217;s visible or just not (hence invisible). To keep things easy, let&#8217;s play that game on a two dimensional area which can be described using a <a href="http://en.wikipedia.org/wiki/Cartesian_coordinate_system" target="_blank">cartesian coordinate system</a>. Further, let&#8217;s use a circle (described as a center with a radius) and a simple point on that coordinate system and try to calculate if that point (as a representative for the position of an object) is within that circle (hence visible from the center of that circle) or just outside of that circle (hence invisible from the center of that circle).</p>
<h4>Business Player</h4>
<p>First, what about defining our main actors in that game? Sounds good? Let&#8217;s start with a simple point. All we need is an <a href="http://gleichmann.wordpress.com/2011/02/05/functional-scala-algebraic-datatypes-sum-and-product-types/" target="_blank">algebraic datatype</a> which just denotes a point within our two dimensional coordinate system:</p>
<p><pre class="brush: scala;">

case class Point( val x :Int, val y :Int )

</pre></p>
<p>As you&#8217;ve might seen, we&#8217;ve annotated our constructor parameters with <em>val</em>, making absolutely clear that a point is an immutable value (hence, we can&#8217;t mutate a given point, but only deriving new points from existing points, e.g. for moving the position of an object). From here, it&#8217;s just a very short jump to come up with the definition of a circle. It&#8217;s just a point to depict the center of that circle and a certain radius. That&#8217;s all for describing a full featured circle in our game world:</p>
<p><pre class="brush: scala;">

case class Circle( val center :Point, val radius :Int )

</pre></p>
<h4>(Pre-) Requisites</h4>
<p>Before we get down to our initial question, what about some small functions in order to warm up? Let&#8217;s say we wanna completely exclude the use of Scala&#8217;s object oriented features and hence don&#8217;t wanna call a<em> Circles</em> getter methods in order to retrieve its center or radius. Hugh? But how we&#8217;re supposed to get those fields then? Well, we could leverage <a href="http://gleichmann.wordpress.com/2011/02/27/functional-scala-pattern-matching-on-product-types/" target="_blank">Pattern Matching</a> in order to retrieve a circles components. Observe:</p>
<p><pre class="brush: scala;">

val radius : Circle =&gt; Int
    =
    circle =&gt; {

        val Circle( center , radius ) = circle
        radius
    }
</pre></p>
<p>What we have here is a so called <em>selector</em> function. In fact, you could see the <em>constructor</em> as a function which takes some arguments and creates a new value of the given type. Then, a <em>selector</em> is nothing else than another function which takes such a constructed value and picks a certain component from <em>within</em> that value. In our case, we did that with a certain form of pattern matching: we just introduced a new value by revealing all its components with a name (<em>center and radius</em>). Those are then bound to the actual values of the given circle. In fact, we could&#8217;ve make use of our famous underscore for the first component, since we&#8217;re only interested in the radius here.</p>
<p>With that knowledge on board, it&#8217;s rather easy to come up with a selector function for the center of a circle:</p>
<p><pre class="brush: scala;">

val center: Circle =&gt; Int
    =
    circle =&gt; {

        val Circle( center , _ ) = circle
        center
    }
</pre></p>
<p>Given those two key players and our two selectors, we only need to come up with an idea on how to detect if a certain point is within the area of a certain circle. There&#8217;s a simple solution, thanks to the genius of Pythagoras &#8230;</p>
<h4>Two points and a distance to go</h4>
<p><a href="http://gleichmann.files.wordpress.com/2011/11/circle031.jpg"><img class="alignleft  wp-image-844" title="circle03" src="http://gleichmann.files.wordpress.com/2011/11/circle031.jpg?w=173&#038;h=162" alt="" width="173" height="162" /></a>It turns out, that the <a href="http://en.wikipedia.org/wiki/Pythagorean_theorem" target="_blank">Pythagorean theorem</a> is a perfect model for calculating the distance of two points (with the center of our circle as the one and the point in question as the other point) in a cartesian coordinate system (what a fortunate coincidence, since our game&#8217;s based on such). If the distance is shorter than the radius of our circle, then the point in question is clearly within the circle (otherwise not).</p>
<p>As you can see from the picture, we simply need to calculate the difference of our two points both x-coordinates and the same with both y-coordinates to come up with the length for the adjacent and the opposite leg (with the distance between our two points as the hypotenuse then). Then the only thing left to do is to solve the famous equation <em>a² + b² = c²</em>. If the point in question is within the circle (or on the circles edge), then a² + b² need to be smaller or equals than <em>radius²</em>.</p>
<p>Let&#8217;s pour our hard earned knowledge into a Function:</p>
<p><pre class="brush: scala;">

val isWithin : ( Circle, Point ) =&gt; Boolean
    =
    ( circle, point ) =&gt; {

        val Point(a, b) = center( circle )
        val Point(x, y) = point

        pow( x-a, 2 ) + pow( y-b, 2 ) &lt;= pow( radius( circle ), 2 )
    }

</pre></p>
<p>Aaahh, a neat function which takes two arguments &#8211; a circle and a point, resulting into a Boolean value which indicates if the given point lies within the circles area. Again we&#8217;re leveraging pattern matching to reveal the x- and y-coordinates of the given center and point. We then simply utilize our knowledge about Phytagoras for the final answer.</p>
<p>With our new function at hand, let&#8217;s just try some scenarios:</p>
<p><pre class="brush: scala;">

val observerView = Circle( Point( 2, 2 ), 3 )

val observesFirstPoint = isWithin( observerView, Point( 3, 4 )               // =&gt; true

val observesSecondPoint = isWithin( observerView, Point( 2, 2 )         // =&gt; true

val observesThirdPoint = isWithin( observerView, Point( 6, 6 )            // =&gt; false

val observesFourthPoint = isWithin( observerView, Point( 8, 2 )         // =&gt; false

</pre></p>
<p>Wow, our function seems to work &#8230; but at what price?</p>
<h2>Spicing up a tasteless Function &#8230;</h2>
<p>If you take a closer look at our scenario, there might be a little annoyance which comes into mind. We always want to know if different objects (points) become visible to always the one and same observer (circle). So we always need to pass the same circle to our function, over and over again. Even worse, since our function does not <em>know</em>, that we&#8217;re always passing the same circle, it also calculates the quadratic power of the circles radius over and over again, which might be a waste of resources.</p>
<p>Can we do better? Yes we can! What if we could say &#8216;here&#8217;s a (fixed) circle. Now provide me a function which always calculates if an arbitrary point is within the area of that (fixed) circle&#8217; ? As a little hint, think about our <em>bronze bullet</em> &#8211; those higher order functions. I bet your bell&#8217;s already ringing, right? What we need is a <em>function maker</em>, a function which produces (and returns) another function! Hey, and as we know that functions are nothing special or better than values of other types, let&#8217;s do it:</p>
<p><pre class="brush: scala;">

val isWithin : Circle =&gt; ( Point =&gt; Boolean )
    =
    circle =&gt; {

        val radSquare = pow( radius( circle ), 2 )
        val Point(a, b) = center( circle )

        point =&gt; {

            val Point(x, y) = point

            pow( x-a, 2 ) + pow( y-b, 2 ) &lt;= radSquare
        }
    }

</pre></p>
<p>Oh boy, not so fast! Let&#8217;s anatomize what we have here and strip it down to its single pieces! The first interesting element is the type signature, given at line 1. The type says that we have a function which just takes a single circle (before the first function arrow) and results into something we&#8217;ll inspect in a moment (all within that round brackets after the first function arrow). So we have clearly a function in front. Now take a closer look at the type of the functions result (all inside that round brackets). But look, it must be again a function, taking a single Point and resulting into a boolean value! Clearly, the whole construction must be our function maker!</p>
<p>Let&#8217;s inspect how it&#8217;s going to produce that function. We can detect it as the last expression (which also becomes the return value in Scala automatically) within the body of our function maker, beginning at line 8 upto line 13.  This function only takes a single point and then starts our well known calculation. An instance (value) of that function is created whenever our function maker is called with a certain circle. And since this ad hoc created, resulting function is anonymous (look, it even lacks a name) it must be a &#8230; tataaa &#8230;<a href="http://gleichmann.wordpress.com/2010/12/05/functional-scala-lambdas-and-other-shortcuts/" target="_blank"> lambda expression</a>!</p>
<p>But wait, where come those values like <em>x</em>, <em>y</em> or even <em>radSquare</em>? Since those values aren&#8217;t defined as arguments of our resulting function, we have some free variables which only got bound by closing over into the lexical scope where the function is created (that is the body of our function maker, were we&#8217;ve calculated the square of the circles radius only once). So the delivered function must be a &#8230; tataaa &#8230; <a href="http://gleichmann.wordpress.com/2010/11/15/functional-scala-closures/" target="_blank">closure</a>!</p>
<p>Now let&#8217;s look how we could bring our function maker into use:</p>
<p><pre class="brush: scala;">
val observerView = Circle( Point( 2, 2 ), 3 )

val observes : Point =&gt; Boolean = isWithin( observerView )

val observesFirstPoint = observes( Point( 3, 4 ) )

val observesSecondPoint = observes( Point( 2, 2 ) )

val observesThirdPoint = observes( Point( 6, 6 ) )

val observesFourthPoint = observes( Point( 8, 2 ) )
</pre></p>
<p>Please direct your attention to line 3, where we just called our function maker <em>isWithin</em> which returns another function <em>observes</em> which in turn can be used further on to test if all those arbitrary points lie in the area of the predefined circle (which is kind of fixed within the resulting function <em>observes</em>)! Of course we could still use our function maker and the resulting function in one go:</p>
<p><pre class="brush: plain;">
val firstObserverView = Circle( Point( 2, 2 ), 3 )

val obervedByFirst = isWithin( firstObserverView )( Point( 3, 4 ) )

...
val secondObserverView = Circle( Point( 17, 21 ), 5 )

val obervedBySecond = isWithin( secondObserverView )( Point( 23, 17 ) )
</pre></p>
<p>So if we want to use our new construction just once for different circles, we can just apply that circle to our function maker, which in turn results into our function for doing the final calculation, which in turn is immediately applied to the given point. Since we do two function calls in a row, we provide those two arguments (one for each function) within two different argument lists.</p>
<h2>Where&#8217;s the curry, mom &#8230; ?</h2>
<p>Now, look where we&#8217;ve come from. We started with a function, taking two arguments, resulting into a boolean value:</p>
<blockquote><p>( Circle , Point ) =&gt; Boolean</p></blockquote>
<p>We then massaged that function into another function which we called a function maker. Now if you look at the type of that higher order function, you&#8217;ll see that they are not so different from each other:</p>
<blockquote><p>Circle =&gt; Point =&gt; Boolean</p></blockquote>
<p>I&#8217;ve omitted the round brackets &#8211; they&#8217;re not needed since our function arrow is right associative (of course you can always keep the brackets for your own clarity). So if we look at the players of both types, they&#8217;re the same! Further, given the same circle and point, the final result also remains the same, no matter if you call the first or second version. We&#8217;ve only <em>translated</em> the first version which takes two arguments (a circle and a point) into a version which is taking a single argument (a circle), resulting into another function which in turn takes a single argument (a point), resulting into a boolean.</p>
<p>We could generalize this idea, taking any function with an arbitrary number of arguments and translate it into a function which just takes the first argument, resulting into a function which just takes the second argument, resulting into another function which just takes the third argument, which &#8230; (you get the idea) &#8230; resulting into the final result.</p>
<p>This transformation process is well known in the functional world where it deserves its own name. It&#8217;s called &#8216;<em>Currying</em>&#8216; (according to the name of <em><a href="http://en.wikipedia.org/wiki/Haskell_Curry">Haskell Brooks Curry</a></em>, a famous mathematician and logician). The result of <em>currying</em> a given function is then called a <em>curried function</em>. In fact, this kind of transformation could be done in a pure mechanical way. Let&#8217;s try to define a function <em>curry</em>, which takes a function of two arguments and returning a curried version of it:</p>
<p><pre class="brush: scala;">
def curry[A,B,C]( func : (A, B) =&gt; C ) : A =&gt; B =&gt; C    =    a =&gt; b =&gt; func( a, b )
</pre></p>
<p>Wow, let&#8217;s take a closer look at it. First of all, we need to fall back to a method definition (starting with a <em>def</em>), since Scala doesn&#8217;t support <a href="http://gleichmann.wordpress.com/2011/01/23/functional-java-polymorphic-functions/" target="_blank">polymorphic functions</a>: because we wanna preserve the given arguments and return types of the function to curry, we need to introduce those types as type parameters. Now look at the  argument <em>func</em> of method <em>curry</em>: it&#8217;s a function, taking two arguments (of type <em>A</em> and <em>B</em>) resulting into a value of type <em>C</em>. The curried version of such a function would be a function taking a single argument of type <em>A</em>, resulting into another function which in turn accepts a single argument of type <em>B</em>, finally resulting into a value of type <em>C</em>. But look at the return type of our <em>curry</em> method &#8211; it&#8217;s exactly of that type &#8211; hurray!  In fact, the method body can&#8217;t do anything other than what the return type already predicts &#8230;</p>
<p>Now we could use our new function <em>curry</em> in order to apply it to our inital version of <em>isWithin</em> &#8230;</p>
<p><pre class="brush: scala;">
val isWithin : ( Circle, Point ) =&gt; Boolean = ...

val curriedIsWithin : Circle =&gt; Point =&gt; Boolean = curry( isWithin )
</pre></p>
<p>So this kind of mechanical currying is surely a no brainer. It&#8217;s so no brained, that it&#8217;s of course already provided within the interface of Scala&#8217;s <a href="http://gleichmann.wordpress.com/2010/11/08/functional-scala-functions-as-objects-as-functions/" target="_blank"><em>FunctionN</em></a> types:</p>
<p><pre class="brush: scala;">
val isWithin : ( Circle, Point ) =&gt; Boolean = ...

val curriedIsWithin : Circle =&gt; Point =&gt; Boolean = isWithin.curried
</pre></p>
<p>You&#8217;ve surely already noticed, that this kind of mechanical currying is only able to solve the problem of not handing a circle (as the first argument) to our function over and over again. It simply pulls the arguments apart, providing a chain of nested function makers which only take one single argument each. Of course it can&#8217;t provide any optimization, e.g. calculating the square of the circles radius only once, serving as a value to close over.</p>
<h2>Summary</h2>
<p>Within this episode, we transformed a given function by hand: we took a function with more than one argument and massaged it into a function (we called it a function maker) which always took a single argument at a time, resulting into another function until there&#8217;s no argument left, resulting into the final result. Again, we saw that functions are nothing better than ordinary values which can be produced and returned by other (then higher order) functions.</p>
<p>We also saw that this kind of transformation can also be done in a more mechanical way, but then lacking some more intelligent separation strategies like optimization of resource usage. Either way, that transformation process is so prominent in the functional world, that it&#8217;s marked with an own name: <em>Currying</em>. We&#8217;ll see some more interesting usage scenarios of Currying and its result &#8211; curried functions &#8211; in some future episodes.</p>
<p>So far we only used Currying on functions. But what about methods? Is there a similar way to produce some kind of <em>curried methods</em> where we could provide only one (or some) arguments at a time? And if so, can we also apply some optimization strategies like we did with our function <em>isWithin</em> or use a function <em>curry</em> to transform a method into a curried one? If you&#8217;re eager to know, that&#8217;s good!  We&#8217;ll solve all those questions in the next episode. Would be glad to see you again &#8230;</p>
<hr />
<p>Side Note<br />
The idea of transforming a function with multiple arguments into a curried one was not invented by Haskell Curry. Curry was only the one which popularized the idea in the field of combinatory logic. The initial idea came from a russian mathematician of name <a href="http://en.wikipedia.org/wiki/Moses_Sch%C3%B6nfinkel">Moses Schönfinkel</a>. So whenever to use <em>Currying</em>, we should not forget about Moses! At least, i guess not calling the process after him, is that <em>Schönfinkeling</em> doesn&#8217;t sound that good &#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gleichmann.wordpress.com/838/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gleichmann.wordpress.com/838/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gleichmann.wordpress.com/838/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gleichmann.wordpress.com/838/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gleichmann.wordpress.com/838/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gleichmann.wordpress.com/838/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gleichmann.wordpress.com/838/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gleichmann.wordpress.com/838/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gleichmann.wordpress.com/838/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gleichmann.wordpress.com/838/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gleichmann.wordpress.com/838/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gleichmann.wordpress.com/838/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gleichmann.wordpress.com/838/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gleichmann.wordpress.com/838/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=838&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gleichmann.wordpress.com/2011/12/04/functional-scala-curried-functions-and-spicy-methods/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/19bad137a600728b7cfeadace9b561fb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mario.gleichmann</media:title>
		</media:content>

		<media:content url="http://gleichmann.files.wordpress.com/2011/11/circle031.jpg" medium="image">
			<media:title type="html">circle03</media:title>
		</media:content>
	</item>
		<item>
		<title>There&#8217;s no average, dumb Java Joe!</title>
		<link>http://gleichmann.wordpress.com/2011/11/27/theres-no-average-dumb-java-joe/</link>
		<comments>http://gleichmann.wordpress.com/2011/11/27/theres-no-average-dumb-java-joe/#comments</comments>
		<pubDate>Sun, 27 Nov 2011 12:01:22 +0000</pubDate>
		<dc:creator>Mario Gleichmann</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[general]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://gleichmann.wordpress.com/?p=835</guid>
		<description><![CDATA[Wow, it&#8217;s been quite a long time since i&#8217;ve blogged the last time (that&#8217;s for the one or other reason that would only bother you, so in essence &#8211; please excuse) . But now i can&#8217;t keep calm any longer, since there&#8217;s an increasing number of articles, claiming that e.g. Functional Programming &#8211; in particular [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=835&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Wow, it&#8217;s been quite a long time since i&#8217;ve blogged the last time (that&#8217;s for the one or other reason that would only bother you, so in essence &#8211; please excuse) . But now i can&#8217;t keep calm any longer, since there&#8217;s an increasing number of articles, claiming that e.g. Functional Programming &#8211; in particular using Scala &#8211; is too hard to get for the average programmer.</p>
<p>First of all,  there isn&#8217;t any &#8216;Java Joe&#8217;  (as a synonym for all those so called &#8216;dumb&#8217; Programmers) out there. Well ok, if it is, then i&#8217;m the ideal protoype of that Joe! And as such  i can tell you, if you&#8217;re willing to learn some new ideas and try to improve your programming skills, than Scala may provide you with a bunch of whole new concepts, not only from the functional world (and i&#8217;m not even talking about type systems here).</p>
<p>In fact, i don&#8217;t care if it&#8217;s Scala, Haskell or any other language, as soon as it may widen my horizon. But i would answer to all those who think Scala is to hard to grasp, that it&#8217;s only a matter of how you would pick up those persons. Granted, it may be difficult to meet those &#8216;newcomers&#8217; at their common ground &#8211; there are some complaints out there that some Scala community members might behave too elitist when it comes to blaming Scala as being too difficult (like &#8216;it&#8217;s not Scala which is too difficult, it&#8217;s only you who don&#8217;t understand it&#8217;).</p>
<p>Frankly, i can follow those complaints. If you&#8217;re willing to learn and may have some problems to grasp some blog posts about Scala (or any other language) or even some code snippets, it is by way no solution to retreat to a position, saying your just to dumb (or lazy or whatsoever) to get it. Spitting out some code snippets or short articles everey now and then is easy &#8211; especially if they come without any context or any larger explanation. That&#8217;s really the easy part! The hard part is meeting that so called average Java Joe at his level and escort him intellectually!</p>
<p>So as a community of Scala fellows (or in any other way), we need to stop  judge over those large herd of programmers as being too dumb. That&#8217;s simply not true! There may be some individuals too sluggish to learn and excel. But for all those others, who may have a hard job and having no chance to deal and become proficient with Scala at day (and therefore have only some hours at night) , we need to provide a way of guidance. And that&#8217;s best done to face that before mentioned reality. It&#8217;s not the people who are dumb. We as a community are dumb if we don&#8217;t react to that reality and welcome those people on their ground!</p>
<h5>Appendix</h5>
<p>In order to walk the talk, i decided to resume my work on writing about functional Scala! Hopefully some may still find it a useful intro to get into the ideas of functional programming in Scala.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gleichmann.wordpress.com/835/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gleichmann.wordpress.com/835/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gleichmann.wordpress.com/835/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gleichmann.wordpress.com/835/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gleichmann.wordpress.com/835/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gleichmann.wordpress.com/835/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gleichmann.wordpress.com/835/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gleichmann.wordpress.com/835/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gleichmann.wordpress.com/835/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gleichmann.wordpress.com/835/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gleichmann.wordpress.com/835/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gleichmann.wordpress.com/835/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gleichmann.wordpress.com/835/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gleichmann.wordpress.com/835/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=835&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gleichmann.wordpress.com/2011/11/27/theres-no-average-dumb-java-joe/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/19bad137a600728b7cfeadace9b561fb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mario.gleichmann</media:title>
		</media:content>
	</item>
		<item>
		<title>Functional Scala: Quiz with Lists &#8211; common list functions, handcraftet</title>
		<link>http://gleichmann.wordpress.com/2011/04/17/functional-scala-quiz-with-lists-common-list-functions-handcraftet/</link>
		<comments>http://gleichmann.wordpress.com/2011/04/17/functional-scala-quiz-with-lists-common-list-functions-handcraftet/#comments</comments>
		<pubDate>Sun, 17 Apr 2011 20:24:08 +0000</pubDate>
		<dc:creator>Mario Gleichmann</dc:creator>
				<category><![CDATA[general]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://gleichmann.wordpress.com/?p=811</guid>
		<description><![CDATA[Welcome to another episode of Functional Scala! As promised within the last episode, we&#8217;re going to take another detailed look at some more commonly used list functions. As we wanna become well acquainted with the functional side of Scala, we&#8217;re again going to implement those list functions one by one. Along the way, we&#8217;ll get [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=811&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Welcome to another episode of Functional Scala!</p>
<p>As promised within the <a href="http://gleichmann.wordpress.com/2011/04/10/functional-scala-essential-list-functions/" target="_blank">last episode</a>, we&#8217;re going to take another detailed look at some more commonly used list functions. As we wanna become well acquainted with the functional side of Scala, we&#8217;re again going to implement those list functions one by one. Along the way, we&#8217;ll get a better and better understanding on how to apply some of the typical tools within the world of functional programming, like pattern matching, recursion or function composition.</p>
<p>As it turned out, most of us learn best in a synthetical way (that is not by dissecting the frog, but to build one). For that, we&#8217;re gonna change the style of the following sections. For every useful function, we&#8217;re first looking at their intended <em>behaviour</em>, maybe along with some exemplary showcases. Only when we grasp the intention, we&#8217;re trying to come up with a sensible idea for their realization and finally with an implementation. You might consider the whole episode like a little quiz and try to come up with your own solutions before you&#8217;ll take a closer look at the presented ones.<span id="more-811"></span></p>
<p>I promise, if you take the approach of thinking first of your own, you&#8217;ll become much more proficient in writing your own list functions in a more functional style after the end of this episode. So start your favoured development environment and have fun to hack &#8230;</p>
<h2>A short refresher</h2>
<p>All solutions are based on our own list-like data structure, which we&#8217;ve <em>invented</em> over the past episodes. For a short refreshment, take a look at the underlying algebraic datatype:</p>
<p><pre class="brush: scala;">
sealed abstract class Lst [+A]{
    def +:[S &gt;: A] ( x :S ) :Lst[S] = new +:( x, this )
}
case object Nl extends Lst[Nothing]
case class +:[A]( x :A, tail :Lst[A] ) extends Lst[A]
</pre></p>
<p>You may detected two changes here: first, we renamed our object which represents the empty list from <em>EmptyLst</em> to <em>Nl</em>. This is first of all a conveniance thing. It&#8217;s shorter and in the tradition of naming the empty list after the latin word for <em>nothing</em> (nil, nihil). Second, we also renamed our value constructor for <em>consing </em>a head to a given list (as the tail of the newly constructed list). It&#8217;s now named <em>+:</em> instead of <em>Cons</em>. This way, we just saved our extractor for doing list deconstruction symmetric to list construction, since we can naturally pattern match on case classes.</p>
<h2>Basic list functions</h2>
<p>Ok, without any further ado, let&#8217;s start with some really basic list functions. We&#8217;ve already encountered some of them within the last episode, so i&#8217;m not gonna repeat them here again.</p>
<h4>empty</h4>
<p>Our first function just provides information if a given list is just the empty list or not. So it should behave like in the following samples:</p>
<p><pre class="brush: scala;">
empty( Nl )  // &gt;&gt; true
...
empty( 1 +: 2 +: 3 +: 4 +: 2 +: 5 +: Nl )  // &gt;&gt; false
...
empty( &quot;a&quot; +: &quot;b&quot; +: &quot;c&quot; +: Nl )  // &gt;&gt; false
</pre></p>
<p>In this case, we just make use of the fact, that Scalas case classes come with a sensible implementation of <em>==</em> for testing two instances for equality:</p>
<p><pre class="brush: scala;">
def empty( lst :Lst[_] ) =  lst == Nl
</pre></p>
<h4>head</h4>
<p>Here, we&#8217;re interested in the head (alas the <em>first </em>element) of a given list. Just look at the examples:</p>
<p><pre class="brush: scala;">
head( Nl )  // &gt;&gt; None
...
empty( 1 +: 2 +: 3 +: 4 +: 2 +: 5 +: Nl )  // &gt;&gt; Some( 1 )
...
empty( &quot;a&quot; +: &quot;b&quot; +: &quot;c&quot; +: Nl )  // &gt;&gt; Some( &quot;a&quot; )
</pre></p>
<p>In this case, we can again leverage pattern matching for simply splitting the problem space into two simpler cases &#8211; the empty list (for which we return None) and a list with at least one element (for which we return just the <em>first </em>element):</p>
<p><pre class="brush: scala;">
def head[A]( lst :Lst[A] ) : Option[A] = lst match {
    case a +: _  =&gt; Some(a)
    case _  =&gt; None
}
</pre></p>
<p>Of course we also could&#8217;ve come up with an unsafe version, which throws an exception in case of an empty list:</p>
<p><pre class="brush: scala;">
def head[A]( lst :Lst[A] ) : A = lst match {
    case a +: _  =&gt; a
    case _  =&gt; error( &quot;no head on empty list&quot; )
}
</pre></p>
<h4>tail</h4>
<p>This is the complement of the <em>head</em> function, which just returns everything but the head.</p>
<p><pre class="brush: scala;">
tail( Nl )  // &gt;&gt; Nl
...
tail( 1 +: 2 +: 3 +: 4 +: 2 +: 5 +: Nl )  // &gt;&gt; 2 +: 3 +: 4 +: 2 +: 5 +: Nl
...
tail( &quot;a&quot; +: &quot;b&quot; +: &quot;c&quot; +; Nl )  // &gt;&gt; &quot;b&quot; +: &quot;c&quot; +: Nl
</pre></p>
<p>The implementation might look like quite similar to the one for <em>head</em>. Maybe pattern matching is a good idea &#8230;</p>
<p><pre class="brush: scala;">
def tail[A]( lst :Lst[A] ) : Lst[A] = lst match{
    case _ +: as  =&gt; as
    case _  =&gt; lst
}
</pre></p>
<h4>init</h4>
<p>You may remember function <em>last </em>from the last episode, which results into the last element of a given list. Now again, <em>init </em>can be seen as the complement of <em>last</em>, which just returns everything but the last element:</p>
<p><pre class="brush: scala;">
init( Nl )  // &gt;&gt; Nl
...
init( 1 +: 2 +: 3 +: 4 +: 2 +: 5 +: Nl )  // &gt;&gt; 1 +: 2 +: 3 +: 4 +: 2 +: Nl
...
init( &quot;a&quot; +: &quot;b&quot; +: &quot;c&quot; +; Nl )  // &gt;&gt; &quot;a&quot; +: &quot;b&quot; +: Nl
</pre></p>
<p>This one might be a bit trickier. Again, we could split the whole problem into some simpler sub cases: for the empty list, init is just again the empty list. The first successful and easiest case would be a list which only consists of two elements, so we could just return a new list without the last element before the empty list. For all other cases (where the list consists of more than two elements) we just call <em>init </em>on the tail of the list (which must consist of at least two elements). This recursive call will result into a list without the last element, for which we just prepend the given head of the list:</p>
<p><pre class="brush: scala;">
def init[A]( lst :Lst[A] ) : Lst[A] = lst match {
    case Nl  =&gt; Nl
    case a +: last +: Nl  =&gt; a +: Nl
    case a +: as  =&gt; a +: init( as )
}
</pre></p>
<h2>List construction</h2>
<p>Within this section, we&#8217;ll regard some functions which will be convenient to use for constructing some special list instances. Some other functions will also construct new list instances based on some already given lists.</p>
<h4>repeat</h4>
<p>Say we wanna create a list which consists repeadetly of one and the same given value (we&#8217;ll see shortly for what this is good for). Since we can&#8217;t produce a list which is going to be produced lazily (this is a topic catched by Scalas <em>Stream</em> type, we&#8217;re also going to detect in some further eposide), we can&#8217;t come up with a <em>potentially infinite</em> list. So in our case we need to give a number for the length of a list for which we&#8217;re saying about how often that value should be repeated within the list:</p>
<p><pre class="brush: scala;">
val as :Lst[String] = repeat( &quot;a&quot;, 4 )  // &gt;&gt; &quot;a&quot; +: &quot;a&quot; +: &quot;a&quot; +: &quot;a&quot; +:Nl
...
val ones :Lst[Int] = repeat( 1, 6 )  // &gt;&gt; 1 +: 1 +: 1 +: 1 +: 1 +: 1 +:Nl
...
val succs :Lst[Int=&gt;Int] = repeat( (x :Int) =&gt; x + 1, 3 )  // &gt;&gt;  (x :Int) =&gt; x + 1  +: (x :Int) =&gt; x + 1  +: ...
</pre></p>
<p>Ok, what about taking an element and a counter and recursively calling repeat by decrementing that counter each time (until we want to repeat that element zero times, which therefor results into an empty list)? Since repeat results into a list, we simply prepend the given value in each recursion step to that produced list:</p>
<p><pre class="brush: scala;">
def repeat[A]( a :A , times :Int ) :Lst[A] = if( times == 0 ) Nl else a +: repeat( a , times - 1 )
</pre></p>
<h4>interval</h4>
<p>Ok, this is a very limited function, since it only creates lists of integer values. In this case, we simply wanna create a list which consists of all integer values from a given starting point upto a given end value (which we  presume to be greater as the starting point). In addition to that, we might also wanna give an increment which determines the spread between two neighbor values within that list. Since it&#8217;s only a simple helper function (as we&#8217;re going to see), let&#8217;s just give an implementation for it directly:</p>
<p><pre class="brush: scala;">
def interval( start :Int, end :Int, step :Int ) :Lst[Int] = ( start, end ) match {
    case( s, e ) if s &gt; e  =&gt; Nl
    case( s, e )  =&gt; s +: interval( s + step, e, step )
}
</pre></p>
<p>Of course we could&#8217;ve come up with a more general version which might operate on arbitrary types allowing for enumerating its elements (and therefore providing a sensible order for its values, too).</p>
<h4>append</h4>
<p>So far, we&#8217;re only <em>prepending</em> a new value to a given list to become the head of a new list. But what if we need to append a new value to be the new last element of a given list. Of course, we also wanna do so in a non-destructive way like we did within the last episode when we inserted a new element at an arbitrary position of a given list. Hey, wait a minute! What was that? If appending is like inserting, only limited to a fixed position (namely the last position within a list), why not simply delegating to  function <em>insertAt</em>? Luckily we&#8217;re able to determine the last position of any given list, simply by using function length, which we&#8217;ve also introdiced in the last episode:</p>
<p><pre class="brush: scala;">
def append[A]( a :A, lst :Lst[A] ) : Lst[A] = insertAt( length( lst ), a, lst )
</pre></p>
<p>Just keep in mind that appending a value to a given list is really expensive (at least for our list-like data structure), since we need to reassemble the whole list while inserting the new value at the last position!</p>
<h4>concat</h4>
<p>Now that we know how to <em>add</em> a single value to a given list (no matter at which side), what about concatenating two lists? In this case we wanna receive a new list which just consists of all elements of both lists.</p>
<p><pre class="brush: scala;">
val ints :Lst[Int] = 1 +: 2 +: 3 +: Nl
val moreInts :Lst[Int] = 6 +: 7 +: 8 +: 9 +: Nl
val strings :Lst[String] = &quot;a&quot; +: &quot;b&quot; +: &quot;c&quot; +: Nl
...
val allInts :Lst[Int] = concat( ints, moreInts )  // &gt;&gt;  1 +: 2 +: 3 +: 6 +: 7 +: 8 +: 9 +: Nl
...
val mixed :Lst[Any] = concat( ints, strings )  // &gt;&gt;  1 +: 2 +: 3 +: &quot;a&quot; +: &quot;b&quot; +: &quot;c&quot; +: Nl
</pre></p>
<p>In this case, we simply prepend the elements of the first list recursively to the second one (which&#8217;s then already concatenated with the rest of the first list):</p>
<p><pre class="brush: scala;">
def concat[A,B&gt;:A]( lxs :Lst[A], lys :Lst[B] ) :Lst[B] = ( lxs, lys ) match {
    case ( Nl, ys )  =&gt; ys
    case ( x +: xs, ys )  =&gt; x +: concat( xs, ys )
}
</pre></p>
<h4>flatten</h4>
<p>We just saw how to concatenate two lists resulting into a single list. What about having more than two lists? Say we have a list of lists which elements should all be collected within a single list.You might see it as flattening the list of lists: the inner lists get dissolved within the outer one. Of course are the original lists not deconstructed! We wanna construct a new list, leaving the outer list as well as the inner lists untouched.</p>
<p>You might see the whole process as concatenating two lists repeatedly until all (inner) lists are concatenated:</p>
<p><pre class="brush: scala;">
def flatten[A]( xxs :Lst[Lst[A]] ) :Lst[A] = xxs match {
    case Nl =&gt; Nl
    case x +: xs =&gt; concat( x, flatten( xs ) )
}
</pre></p>
<h2>Sublists</h2>
<p>As the last section within this episode, we&#8217;ll take a closer look at some functions which will deliver a certain sublist for a given list.</p>
<h4>take</h4>
<p>Imagine we need a function which just returns the first n elements of a given list. So clearly we need to give a number how many elements we wanna take from a given list and the list from which the elements are taken from:</p>
<p><pre class="brush: scala;">
val ints :Lst[Int] = 1 +: 2 +: 3 +: +: 4 +: 5 +: Nl
...
val firstThree :Lst[Int] = take( 3, ints )  // &gt;&gt; 1 +: 2 +: 3 +: Nl
...
val moreThanExists :Lst[Int] = take( 10, ints )  // &gt;&gt; 1 +: 2 +: 3 +: +: 4 +: 5 +: Nl
...
val nope = take( 0, ints )  // =&gt; Nl
</pre></p>
<p>Let&#8217;s try to split the problem into some simpler sub problems, once more: first, if we want to take some elements from the empty list, we surely can&#8217;t deliver anything else as the empty list itself. second, if we want to take zero elements from any given list, we again receive only the empty list. Finally, if we want an arbitrary number from a non-empty list, we just deliver the first element of the list and take a a decremented number of elements from the rest of the list:</p>
<p><pre class="brush: scala;">
def take[A]( count :Int, lst :Lst[A] ) :Lst[A] = ( count, lst ) match {
    case ( _ , Nl )  =&gt; Nl
    case ( 0 , _ )  =&gt; Nl
    case ( i, a +: as )  =&gt; a +: take( i-1, as )
}
</pre></p>
<h4>drop</h4>
<p>This one is just the opposite of function <em>take</em>. this time we don&#8217;t wanna take the first n elements but drop them, resulting into a list with all elements but the first n ones.</p>
<p>The cases here are almost the same: droping from an empty list results into an empty list. Second, dropping zero elements from a given list just result into that list. And finally, dropping an arbitrary number of elements from a given list is just omitting the head of the list and dropping a decremented number from the rest of the list:</p>
<p><pre class="brush: scala;">
def drop[A]( count :Int, lst :Lst[A] ) :Lst[A] = ( count, lst ) match {
    case ( _ , Nl )  =&gt; Nl
    case ( 0 , as )  =&gt; as
    case ( i, a +: as )  =&gt; drop( i-1, as )
}
</pre></p>
<h4>splitAt</h4>
<p>Here, we wanna split a given list at a certain position, resulting into a pair of two sublists. The first sublist will contain all elements from head until the element before the position to split. The second one will contain all elements from the position to split upto the last element:</p>
<p><pre class="brush: scala;">
val ints :Lst[Int] = 1 +: 2 +: 3 +: 4 +: 5 +: Nl
...
val (firstTwo,lastThree) = splitAt( 2, ints )  // &gt;&gt; ( 1 +: 2 +: Nl  ,  3 +: 4 +: 5 +: Nl )
</pre></p>
<p>You may wanna think back to those two introduced functions <em>take</em> and <em>drop</em>: Splitting a list can be seen as <em>taking</em> some elements for the first sublist and <em>droping</em> them for the second sublist. So here we go:</p>
<p><pre class="brush: scala;">
def splitAt[A]( pos :Int, lst :Lst[A] ) : (Lst[A],Lst[A]) = ( take( pos, lst ), drop( pos, lst ) )
</pre></p>
<p>Of course you may say, that we&#8217;ll traversionf the original list twice (well, in the worst case for splitting near the end of a list). First for taking the first n elements and then again for dropping them. Of course we could come up with another implementation, which just traverses the list only once:</p>
<p><pre class="brush: scala;">
def splitAt[A]( pos :Int, lst :Lst[A] ) : (Lst[A],Lst[A]) = ( pos, lst) match {
    case( _ , Nl )      =&gt; (Nl,Nl)
    case( 0, as )      =&gt; ( Nl, as )
    case( i, a +: as ) =&gt; val (p1,p2) = splitAt( i-1, as ); ( a +: p1, p2 )
}
</pre></p>
<p>See that thirs case expression? It&#8217;s a bit ugly since we need to put prepending the given head after the recursive split for the rest of the list (otherwise you would end up with a reversed list)</p>
<h2>Summary</h2>
<p>We could continue with that quiz for hours and hours. There are far more useful list functions we haven&#8217;t discovered yet! Hopefully you did some ruminations and experimentation for yourself for getting an even better understanding and feeling on how to operate on lists in a more functional style.</p>
<p>In this episode we just saw some of those commonly used list functions and gave a rather straightforward implementation. We did all this by only using pattern matching, recursion and delegation to some other known functions.</p>
<p>We&#8217;re by far not at the end. As promised within the last episode, we&#8217;ll encounter some very powerful functions which we&#8217;ll levrage to build most of the functions we discovered today in a more concise (but also more abstract) way!  But before we&#8217;ll get there, we need to extend our functional tool box. We&#8217;ll see how to kind of <em>derive</em> new functions out of some already given functions by using currying. Don&#8217;t be afraid! It&#8217;s not about indian food but receiving another mighty tool which allows us to become an even more powerful apprentice of functional programming in Scala. So hope to see you there &#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gleichmann.wordpress.com/811/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gleichmann.wordpress.com/811/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gleichmann.wordpress.com/811/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gleichmann.wordpress.com/811/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gleichmann.wordpress.com/811/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gleichmann.wordpress.com/811/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gleichmann.wordpress.com/811/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gleichmann.wordpress.com/811/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gleichmann.wordpress.com/811/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gleichmann.wordpress.com/811/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gleichmann.wordpress.com/811/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gleichmann.wordpress.com/811/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gleichmann.wordpress.com/811/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gleichmann.wordpress.com/811/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=811&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gleichmann.wordpress.com/2011/04/17/functional-scala-quiz-with-lists-common-list-functions-handcraftet/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/19bad137a600728b7cfeadace9b561fb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mario.gleichmann</media:title>
		</media:content>
	</item>
		<item>
		<title>Functional Scala: Essential list functions</title>
		<link>http://gleichmann.wordpress.com/2011/04/10/functional-scala-essential-list-functions/</link>
		<comments>http://gleichmann.wordpress.com/2011/04/10/functional-scala-essential-list-functions/#comments</comments>
		<pubDate>Sun, 10 Apr 2011 14:08:41 +0000</pubDate>
		<dc:creator>Mario Gleichmann</dc:creator>
				<category><![CDATA[general]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://gleichmann.wordpress.com/?p=797</guid>
		<description><![CDATA[In the last two episodes we came up with the basic idea of persistent (read immutable) list-like data structures and how to construct and deconstruct (read pattern match) them using a sugarized notational form. We also talked big about their non-destructive nature when it comes to e.g. updating a given list or removing some elements. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=797&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In the last <a href="https://gleichmann.wordpress.com/2011/03/20/functional-scala-tinkerbell-frogs-and-lists/" target="_blank">two</a> <a href="https://gleichmann.wordpress.com/2011/04/02/functional-scala-list-sugarization/" target="_blank">episodes</a> we came up with the basic idea of persistent (read immutable) list-like data structures and how to construct and deconstruct (read pattern match) them using a sugarized notational form. We also talked big about their non-destructive nature when it comes to e.g. updating a given list or removing some elements. In this episode, we&#8217;ll finally inspect some of those commonly used list functions. While we&#8217;re going to reimplement the most essential ones,  you&#8217;ll hopefully get a better feeling for the  basic principles and characteristics which build the foundation for operating on persistent data structures in a non-destructive way (preserving the structure of given list values).<span id="more-797"></span></p>
<h3>Retrieving an element</h3>
<p>For a smooth entry into the world of functions on persistent list structures, let&#8217;s first take a look at some non-destructive functions. First we might wanna know if a certain value is an element of a given list. Again we&#8217;re going to cheat a bit, since we&#8217;ll make an implicit assumption that the elements of a list can be tested for equality using <em>==</em> (we&#8217;ll adress that issue in more detail when looking at type classes):</p>
<p><pre class="brush: scala;">
def element[A]( x :A, lst :Lst[A] ) : Boolean = lst match {
    case EmptyLst  =&gt; false
    case a +: _  if( a == x )  =&gt; true
    case _ +: as  =&gt; element( x, as )
}
</pre></p>
<p>That wasn&#8217;t too difficult. For getting an even better feeling (and might see some recurring patterns), let&#8217;s take another look at a read-only function: it&#8217;s surely comfortable to have a function for retrieving a certain element within a given list. Typically, a list structure preserves the order in which their elements got <em>inserted</em>. Let&#8217;s say the element at the head of the list sits on position zero. The next element (which is the head of the lists tail) is at position one and so on and so on. So our function clearly needs two arguments: the position of the element we wanna retrieve and the list itself. Again, we want to preserve the type of the element which is going to be returned, so we&#8217;ll use parametric polymorphism. We also need to handle the absence of a reasonable return value (that is requesting a position which is out of scope for a given list), so we&#8217;ll again returning a value of type Option, parameterized with the type of the lists content. Just watch the following definition for a first feeling:</p>
<p><pre class="brush: scala;">
def elemAt[A]( pos :Int, lst :Lst[A] ) :Option[A] = ( lst, pos ) match {
    case( EmptyLst , _ )  =&gt; None
    case( a +: _ , 0 )  =&gt; Some( a )
    case( _ +: as , i )  =&gt; elemAt( i-1, as )
}
</pre></p>
<p>So what&#8217;s going on here? We&#8217;ll just make use of the recursive structure which is given by the value constructors of our list type. If we&#8217;re requesting an arbitrary position on an empty List (line 2), we can only return <em>None</em>, since we have no element to give. Otherwise, we&#8217;re trying to step through the list until we&#8217;re reaching the requested position: If we request position zero on a given list (line 3), then we&#8217;re immediately done, since we only need to return the head of the given list. For any other position (line 4) we can&#8217;t deliver the lists head but need to step into the tail of the given list (which&#8217;s also a list) recursively, while also reducing the position which is requested within the rest of the list.</p>
<h3>Inserting an element</h3>
<p>Again, we just saw a very natural way for operating on recursive, algebraic datatypes. Since pattern matching can be seen as the counterpart of list construction, we used it for reasoning and react upon the structure of a given list instance: we just splitted the <em>problem </em>into three smaller problem cases which we can handle independently. Secondly we just reflected the recursive nature of our datatype by defining a recursive function which just makes use of the fact that the tail of a list is also a list which can be treated in the same way.</p>
<p>Now that we saw a very natural way for operating on our list type, let&#8217;s see if we&#8217;re able to make use of it when trying to operate on a list which typically <em>destroys </em>the structure of a given list instance in an imperative environment. As we&#8217;ve said, a persistent data structure represents an immutable value. So every operation &#8211; like inserting another element at an arbitrary position into a given list &#8211; just results into a new version (read a new value) of a list.</p>
<p>So how could we achieve it? Maybe we could take a look at our three cases we used for retrieving an element within a given list. In doing so, we might find an answer for all of those three smaller <em>problems</em>:</p>
<ol>
<li>Inserting an element into the empty list, at an arbitrary position<br />
In this case, we might simply return a new list which just consists of the new element , prepended to the empty list. We just don&#8217;t care about the position, since we already <em>arrived </em>at the end of the list.</li>
<li>Inserting an element into a given list at position zero<br />
In this case, we also just prepend the new element to the given list. The result is a new list with the new element as head and the given list as the tail. Of course, the old list instance isn&#8217;t destroyed since we only constructed a new list version which <em>refers </em>to the old list version as its tail.</li>
<li>Inserting an element into a given list at any other position<br />
In this case, we can&#8217;t simply prepend the new element as the head of a new list. Like we already did, we also need to step through the rest of the list, until we reached the right position. And here comes the exciting part: while we&#8217;re stepping though the list, we just reassemble all the list elements we&#8217;ve already passed so far, creating a new list version. We&#8217;ll doing this in a recursice way, by just prepending every element we&#8217;re passing to the list which results from the recursive call of inserting the element into the rest of the list (which should result into a list, were the new element is already inserted successfully).</li>
</ol>
<p>Now we achieved a master plan for inserting elements into a given list, just resulting into a new list which also holds a new element at the requested position. Implementing that function should be easy now:</p>
<p><pre class="brush: scala;">
def insertAt[A,B&gt;:A](  pos :Int, b :B, lst :Lst[A] ) :Lst[B] = ( lst, pos ) match {
    case ( EmptyLst , _ )  =&gt;	b +: EmptyLst
    case( as , 0 )  =&gt; b +: as
    case( a +: as , i )  =&gt; a +: insertAt( i-1, b, as )
}
</pre></p>
<p>Remember the covariant nature of our list type? Again, we reflected that fact just by allowing to insert an arbitrary element for a possible supertype of the given type of the lists content. The function then results into a new list which holds for the most specific type for the new element and the given elements. Most important, we didnt destroyed the old list version. We only constructed a new list instance by reassembling every single element on our way to the position for the new element to insert. When we reached that position, we simply result into a list which refers to that new element as the head and refering the rest of the given list as the tail.</p>
<p>You might see the whole process splitted into two phases: reconstruction of a new list by reassembling all elements until we reached the position for the new element and just refering (and thus sharing with the original list version) to the rest of the list after we reached the position for the new element. So for inserting a new element near the start of a list you might need to reassemble only a few list elements (sharing the most part of the list with the former version), while inserting a new element at the end of a list results in reassembling all given elements of the original list value. So in this worst case the cost for inserting a new element (the way we did above) raise linear with the number of the lists elements.</p>
<h3>Replacing an element</h3>
<p>We shouldn&#8217;t have any new poblems for that kind of quest. It&#8217;s quite similar to the idea of inserting a new element. The only difference is to just skip the given element at the requested position when reassembling the new list version. Observe:</p>
<p><pre class="brush: scala;">
def replaceAt[A,B&gt;:A]( pos :Int, b:B, lst :Lst[A] ) :Lst[B] = ( lst, pos ) match {
    case ( EmptyLst , _ )  =&gt;	b +: EmptyLst
    case ( a +: as, 0 ) =&gt; b +: as
    case ( a +: as, i ) =&gt; a +: replaceAt( i-1, b, as )
}
</pre></p>
<p>See the pattern at line 3. There we now deconstructed the list into its head and tail, just to leave out the head when it comes to constructing the new list on the right side of the case expression!</p>
<h3>Removing an element</h3>
<p>Removing an element should be very similar to replacing an element. What? Yep, it&#8217;s like replacing without any new element (to replace with) at all. Just watch:</p>
<p><pre class="brush: scala;">
def removeAt[A]( pos :Int, lst :Lst[A] ) :Lst[A] = ( lst, pos ) match {
   case ( EmptyLst , _ )  =&gt; EmptyLst
   case ( a +: as, 0 )  =&gt; as
   case ( a +: as, i )  =&gt; a +: removeAt( i-1, as )
}
</pre></p>
<p>Another way would be to give an arbitrary value which is intented to be removed from the list if it&#8217;s an element of it. Again, we&#8217;ll rely on == for identifying that value within a given list instance. The idea is again very similar to element removal on a certain position. In this case, we just regard every element while stepping through the list:</p>
<p><pre class="brush: scala;">
def remove[A]( x :A, lst :Lst[A] ) :Lst[A] = lst match{
    case EmptyList  =&gt; EmptyLst
    case a +: as if( a == x )  =&gt; remove( x, as )
    case a +: as  =&gt; a +: remove( x, as )
}
</pre></p>
<h3>Summary</h3>
<p>In this episode, we saw how to come up with a bulk of some of the most common, essential list functions, operating on lists in a non-destructive way. There, we detected some common patterns.</p>
<p>First, we used pattern matching for reasoning and reacting upon the structure of a given list instance, allowing us to split the <em>problem </em>into some smaller problem cases which we can handle independently.</p>
<p>Second, our functions reflected the recursive nature of our datatype. At least one case within our function was defined in a recursice way, which just makes use of the fact that the tail of a list is also a list which can be treated by the function in the very same way.</p>
<p>And finally, we saw the non-destructive <em>processing </em>of a given list version, mostly reflected by reassembling a new list structure by the given elements of the original version until we reached a situation (or case) were we could handle the problem immediately, followed by simply referring to the rest of the original list, which can be seen as structural sharing this part of the list between the old and the new list version. In either way, we always come up with a new list value which is kind of derived from the old list. All of the functions we&#8217;ve looked so far are leaving the original version untouched, which is so to say the essence of persistent data structures.</p>
<p>Of course there are many more list functions which we haven&#8217;t considered yet. What about concatenating two list values for example? Not only for that, we&#8217;re going to explore some very powerful functions, which will constitute the basis for a bunch of other functions on lists (like concatenation). That will be the topic for the next episode. So stay tuned &#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gleichmann.wordpress.com/797/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gleichmann.wordpress.com/797/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gleichmann.wordpress.com/797/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gleichmann.wordpress.com/797/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gleichmann.wordpress.com/797/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gleichmann.wordpress.com/797/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gleichmann.wordpress.com/797/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gleichmann.wordpress.com/797/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gleichmann.wordpress.com/797/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gleichmann.wordpress.com/797/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gleichmann.wordpress.com/797/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gleichmann.wordpress.com/797/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gleichmann.wordpress.com/797/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gleichmann.wordpress.com/797/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=797&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gleichmann.wordpress.com/2011/04/10/functional-scala-essential-list-functions/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/19bad137a600728b7cfeadace9b561fb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mario.gleichmann</media:title>
		</media:content>
	</item>
		<item>
		<title>Functional Scala: List sugarization</title>
		<link>http://gleichmann.wordpress.com/2011/04/02/functional-scala-list-sugarization/</link>
		<comments>http://gleichmann.wordpress.com/2011/04/02/functional-scala-list-sugarization/#comments</comments>
		<pubDate>Sat, 02 Apr 2011 16:00:44 +0000</pubDate>
		<dc:creator>Mario Gleichmann</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://gleichmann.wordpress.com/?p=764</guid>
		<description><![CDATA[In the last episode we started to look at persistent list-like data structures. We came up with an algebraic datatype which allows to construct arbitrary lists, featuring parametric polymorphism with regard to the type of the lists content. So far, we didn&#8217;t see the non-destructive nature of those datatypes when it comes to updating a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=764&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://gleichmann.wordpress.com/2011/03/20/functional-scala-tinkerbell-frogs-and-lists/" target="_blank">last episode</a> we started to look at persistent list-like data structures. We came up with an algebraic datatype which allows to construct arbitrary lists, featuring parametric polymorphism with regard to the type of the lists content. So far, we didn&#8217;t see the non-destructive nature of those datatypes when it comes to updating a given list or removing some elements.</p>
<p>Bear with me. We&#8217;re going to inspect a bulk of widely accepted, commonly used list functions, operating on persistent data structures in a non-destructive way! But before, we&#8217;ll need to prepare ourself with a set of tools for an easier way of tinkering with our list-like data structure.<span id="more-764"></span></p>
<h3>Syntactic sugar</h3>
<p>First of all, let&#8217;s add some syntactic sugar to our list type. You may remember that building a list was a bit cumbersome. We always needed to use our value constructor <em>Cons </em>in a nested form, beginning with the empty list object <em>EmptyLst</em> as the final tail:</p>
<p><pre class="brush: scala;">
val intList :Lst[Int] = Cons( 1, Cons( 2, Cons( 3, EmptyLst ) ) )
val stringList :Lst[String] = Cons( &quot;a&quot;, Cons( &quot;b&quot;, Cons( &quot;c&quot;, EmptyLst ) ) )
</pre></p>
<p>Clearly we can see the recursive structure of our list type, but declaring or reading a certain list instance seems a bit laborious. Unfortunately, Scala doesn&#8217;t allow infix notation for function application, so we can&#8217;t come up with a function which simply prepends another element to a given list and use that for cushy list construction, like<em> 1 &#8216;prep&#8217; 2 &#8216;prep&#8217; EmptyLst</em>. For a kind of <em>workaround</em>, we&#8217;ll now leave the pure functional path for a moment and make use of Scalas object oriented features. What about adding a (pure) method to our list type, which let&#8217;s us apply a new element to a given list instance. The method then simply constructs a new list for us by prepending the passed value as the new head and the given list as the tail. Observe:</p>
<p><pre class="brush: scala;">
sealed abstract class Lst [+A]{
    // compile error: covariant type A occurs in contravariant position in type A of value x
    def +: ( x :A ) :Lst[A] = Cons( x, this )
}
</pre></p>
<p>Before we get to that compile error, let&#8217;s firstly take a look at the methods <em>+:</em> core intention: we just wanna apply a new value <em>x</em> to our <em>function</em>, which should be of the same type as the already given type of the given lists content. We then simply construct and return a new list value which consists of the new element <em>x</em> as the head and the given list as the tail, just as said. It&#8217;s just a helper function which hides the manual list construction based on the value constructor <em>Cons</em>.</p>
<p>Unfortunately it won&#8217;t compile! Remember the last episode were we introduced covariance for type parameter <em>A</em>? We did so, because we wanted to share our empty List as a single object for all of our list instances as the final tail. For that, this single object needed to be a subtype for all possible list instances in <em>A</em>. Now we have to play the game of covariance for <em>A</em>! And this means, that we have to allow to prepend an element which might be of a supertype of <em>A</em>. In that case, the newly constructed list is type parametrized by that more general type. So the following definition should work, since we just leverage Scalas power to simply apply a lower type bound for our new element to prepend:</p>
<p><pre class="brush: scala;">
sealed abstract class Lst [+A]{
    def +:[S &gt;: A] ( x :S ) :Lst[S] = Cons( x, this )
}
</pre></p>
<p>Now <em>x</em> can be of any type <em>S</em> which may be of the same type as <em>A</em> or a supertype of <em>A</em>. We finally result into a list which contains elements, for which <em>S</em> is the most specific type. Now, with our new helper method <em>+:</em> at hand, list construction can be done in a more concise way:</p>
<p><pre class="brush: scala;">
val lst :Lst[Int] = 1 +: 2 +: 3 +: 4 +: 5 +: EmptyLst
val anotherLst :Lst[Any] = 1 +: &quot;a&quot; +: 2 +: &quot;b&quot; +: EmptyLst
</pre></p>
<p>Ahhh, now we got a much shorter way of defining new list instances. As you could see with <em>anotherLst</em>, the type of the lists content is <em>Any</em>, since it&#8217;s the most specific type for <em>Int</em> and <em>String</em>. There&#8217;s only one little thing that may get you into baffling mode. Taking above list <em>anotherLst</em> for example, it looks like we&#8217;re calling method <em>+:</em> on value <em>1</em> for prepending it to value <em>&#8220;a&#8221;</em>. But that&#8217;s not the case! As soon as our method ends with a colon, it&#8217;s gonna be called in a right associative manner. That is, <em>+:</em> is first called on <em>EmptyLst </em>for prepending value <em>&#8220;b&#8221;</em>, resulting into an instance of <em>Lst[String]</em>. Then <em>+:</em> is again called on that list instance, prepending value <em>2</em>. Since that value is of type <em>Int</em>, we end up with a new list of type <em>Lst[Any]</em> and so on and so on &#8230;</p>
<h3>Pattern matching</h3>
<p>Ok, now we got a fancy tool for list construction, but what about deconstructing lists by pattern matching? As you surely remember <a href="http://gleichmann.wordpress.com/2011/02/13/functional-scala-pattern-matching-the-basics/" target="_blank">from</a> <a href="http://gleichmann.wordpress.com/2011/02/20/functional-scala-combinatoric-pattern-matching/" target="_blank">some</a> <a href="http://gleichmann.wordpress.com/2011/02/27/functional-scala-pattern-matching-on-product-types/" target="_blank">older</a> <a href="http://gleichmann.wordpress.com/2011/03/06/functional-scala-a-little-expression-language-with-algebraic-datatypes-and-pattern-matching/" target="_blank">episodes</a>, pattern matching is one of the main tools for operating on algebraic datatypes. And since our list type is defined in the tradition of algebraic datatypes, we shouldn&#8217;t have any problems to use pattern matching upon the given value constructors of our list type. For example, let&#8217;s determine the length of a given list by defining an appropriate function:</p>
<p><pre class="brush: scala;">
val length : Lst[_] =&gt; Int = _ match{
    case EmptyLst =&gt; 0
    case Cons( _ , tail ) =&gt; 1 + length( tail )
}
</pre></p>
<p>That wasn&#8217;t too complicated. We just accept arbitrary lists with an arbitrary content type by stating an existential type for our list argument in the functions signature. We then simply deconstruct the given list, decomposing it into its head and tail (the rest of the list) until we reach the empty list, each time adding 1 to the length for each element we&#8217;ll find all the way down. If you&#8217;re not worrying about the unbalance for using value constructor <em>Cons </em>for deconstruction while using our new method <em>+:</em> for construction, everything is fine. But things get more ugly pretty fast again, if we need to pattern match against more than a single head and tail of a list.</p>
<p>For example, let&#8217;s write a function which delivers the last element of a list. For doing that, we need to get past two considerations. First, we wanna preserve the type of the lists content. If we want to retrieve the last element for a list of Strings, we should return a String. If it&#8217;s a list of Ints, we&#8217;d like to return an Int value! For that to achieve, our function need to be polymorphic in the type of the lists content. As we figured out in <a href="http://gleichmann.wordpress.com/2011/01/23/functional-java-polymorphic-functions/" target="_blank">an earlier episode</a>, this is best done (and even the idiomatic way) by providing a polymorphic method instead of a function value within a polymorphic environment:</p>
<p><pre class="brush: scala;">
def last[A]( lst :Lst[A] ) : A = ...
</pre></p>
<p>Second, how do we wanna operate upon an empty list, since there&#8217;s simply no last element which we could hand out. For handling the possible absence of a last element we&#8217;re going to use type <em>Option</em>,  which suits this kind of dilemma to a T: we simply return a value of <em>Option[A]</em> which is just <em>None </em>in the case of an empty list. That way, we stay really honest about the type of our return value (while simply returning null wouldn&#8217;t be honest at all,<a href="http://channel9.msdn.com/Shows/Going+Deep/Erik-Meijer-Functional-Programming" target="_blank"> as Dr. Erik Meijer now would say</a>). So we end up with a function like this:</p>
<p><pre class="brush: scala;">
def last[A]( lst :Lst[A] ) : Option[A] = lst match {
    case EmptyLst =&gt; None
    case Cons( x, EmptyLst ) =&gt; Some( x )
    case Cons( _ , Cons( x, xs ) ) =&gt; last( Cons( x, xs ) )
}
</pre></p>
<p>Admitted, it&#8217;s a somewhat contrived example, since we needn&#8217;t to pattern match againt the first two elements and the rest of the list explicitly (as you may see in the third case expression at line four). Let&#8217;s simply say we wanted to communicate that constitution of the list (in that the list contains at least two elements) in a very definite way. Anyway, you might see, that using value constructor <em>Cons </em>for deconstructing more than a single head and tail leads again to very cumbersome patterns!</p>
<p>Fortunately, we<a href="http://gleichmann.wordpress.com/2011/03/13/functional-scala-expressions-extensions-and-extractors/" target="_blank"> already know about Extractors</a> as another way to define patterns which are somewhat independent of the structure of value constructors. So what speaks against an Extractor which allows us to form patterns, kind of mimicing the way we construct lists via method <em>+:</em> ? Therefore, we just name such an Extractor object like our construction method. Just watch:</p>
<p><pre class="brush: scala;">
object +: {
    def unapply[A]( x: Lst[A] ) : Option[ (A, Lst[A]) ] = x match {
        case Cons( hd, tl ) =&gt; Some( (hd, tl) )
        case _ =&gt; None
    }
}
</pre></p>
<p>So now we just could come up with a nice pattern declaration which really looks like list notations at the construction side. This way, we just recovered the balance between the form of construction and deconstruction:</p>
<p><pre class="brush: scala;">
def last[A]( lst :Lst[A] ) : Option[A] = lst match {
    case EmptyLst =&gt; None
    case x +: EmptyLst=&gt; Some( x )
    case _ +: x +: xs =&gt; last( x +: xs )
}
</pre></p>
<p>Now pattern matching is fun again, since forming patterns don&#8217;t differ from forming list instances any more. In fact, we could kind of hide our value constructor <em>Cons </em>from the eyes of our users. We simply don&#8217;t need to know about it, wether on construction, nor on deconstruction side.</p>
<p>Now, to bring this episode to a close, let&#8217;s define just another little function <em>show</em>, which simply converts a given list into an appropriate string representation. This string representation might also resemble the form of a list, like we use for construction and deconstruction:</p>
<p><pre class="brush: scala;">
def show( lst :Lst[_] ) :String = lst match {
    case EmptyLst =&gt; &quot;EmptyLst&quot;
    case x +: xs 	=&gt;  x + &quot; +: &quot; + show( xs )
}
...
val lst :Lst[Int] = 1 +: 2 +: 3 +: 4 +: 5 +: EmptyLst
...
val lstShow :String = show( lst )   // results into ''1 +: 2 +: 3 +: 4 +: 5 +: EmptyLst''
</pre></p>
<p>Here we just cheated a bit, since we rely on method <em>toString </em>for the string representation of the given list values. To get back to a more functional style, there should be another <em>show </em>function for turning those values into an appropriate string representation, too. The question is how do we enforce that such a function need to exist for any list value type. There we just detected the need for some more powerful constraints which we&#8217;ll adress when looking at type classes (but that will be within an episode in the distant future).</p>
<h3>Summary</h3>
<p>In this eposide we just set the stage for writing all those commonly used list functions in a more comfortable way.</p>
<p>First, we added some syntactic sugar for easier list construction. For there&#8217;s no way of doing infix function application, we provided an appropriate helper method for our list type which simply takes a new element and builds a new list, obeying covariance. We&#8217;re now able to construct a new list in a right associative way, since Scala calls every method which ends with a colon on the object at the right side of the method call.</p>
<p>We finally found a nice way to form pattern expressions to use within pattern matching which kind of mimic the same notation as for list construction. There, we just leveraged the idea of Extractors for providing an appropriate instance which is named after the method for building lists by prepending values. This way, we kind of established a nice notational balance between list construction and deconstruction.</p>
<p>Now we got some nice tools for defining a whole bunch of list functions, like inserting, replacing or removing elements in an easy, concise way. As you&#8217;ll see, we&#8217;ll doing so in a completely non-destructive way. But that&#8217;s the topic for another episode. Hope to see you there &#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gleichmann.wordpress.com/764/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gleichmann.wordpress.com/764/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gleichmann.wordpress.com/764/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gleichmann.wordpress.com/764/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gleichmann.wordpress.com/764/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gleichmann.wordpress.com/764/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gleichmann.wordpress.com/764/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gleichmann.wordpress.com/764/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gleichmann.wordpress.com/764/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gleichmann.wordpress.com/764/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gleichmann.wordpress.com/764/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gleichmann.wordpress.com/764/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gleichmann.wordpress.com/764/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gleichmann.wordpress.com/764/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=764&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gleichmann.wordpress.com/2011/04/02/functional-scala-list-sugarization/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/19bad137a600728b7cfeadace9b561fb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mario.gleichmann</media:title>
		</media:content>
	</item>
		<item>
		<title>Functional Scala: Tinkerbell, Frogs and Lists</title>
		<link>http://gleichmann.wordpress.com/2011/03/20/functional-scala-tinkerbell-frogs-and-lists/</link>
		<comments>http://gleichmann.wordpress.com/2011/03/20/functional-scala-tinkerbell-frogs-and-lists/#comments</comments>
		<pubDate>Sun, 20 Mar 2011 18:25:19 +0000</pubDate>
		<dc:creator>Mario Gleichmann</dc:creator>
				<category><![CDATA[general]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://gleichmann.wordpress.com/?p=752</guid>
		<description><![CDATA[Welcome to another episode of Functional Scala! What do you know about Frogs? Well, i mean beyond the most common facts you learn from books. One way to learn more about Frogs might be to dissect one, as you may have done back in school. That would be the analytic way. But there&#8217;s a better [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=752&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Welcome to another episode of Functional Scala!</p>
<p>What do you know about Frogs? Well, i mean beyond the most common facts you learn from books. One way to learn more about Frogs might be to dissect one, as you may have done back in school. That would be the <em>analytic</em> way. But there&#8217;s a better way: if you really want to learn about the nature of a frog, you should build one! By building a being that has froglike characteristics, you&#8217;re going to learn what makes a frog a frog and how frogs are adapted to their particular environment. It&#8217;s a perfect example of learning by <em>synthesis</em>!</p>
<p>Well, as this isn&#8217;t a series about biology but about Functional Programming with Scala, we&#8217;re going to focus on another research object, which will be list-like data structures in a functional environment. We&#8217;re going to construct a simple, <em>functional</em> list type and explore its characteristics along the way. So let&#8217;s start and play Tinkerbell &#8230;<span id="more-752"></span></p>
<h3>Functional vs imperative data structures</h3>
<p>If you&#8217;re coming from a more imperative background, chances are good that you already heard of a List. Unfortunately, they are also implemented in an imperative way. What does that mean? Take a look at the following examples in Java:</p>
<p><pre class="brush: java;">
List primes = new LinkedList(){{ add(3); add(5); add(7); }};
List oddNums = primes;
...
oddNums.add( 15 );
primes.add( 2 );
</pre></p>
<p>Uhm, what happened? You can&#8217;t do that! Well, i shouldn&#8217;t do that, but i&#8217;m allowed to! What we have here is a nice example of sharing a single list instance. Holding more than one reference to a single list isn&#8217;t bad as such. But it might get really, really bad when performing so called <em>destructive updates</em> in an unproper way! In this case, an update to <em>oddNums </em>will destroy the initial structure of the original list &#8211; the <em>old version</em> of the data structure won&#8217;t be available any longer. There&#8217;s simply only one version of that list instance, which gets updated <em>by assignment</em>. In doing so, we just triggered a kind of side effect, since <em>primes </em>also refers to that one and only, <em>mutable</em> version of our list! A data structure which only supports a single version at a time &#8211; even across updates &#8211; is called <em>ephemeral</em> and it turns out, that most imperative data structures are ephemeral.</p>
<p>While reading the last section, this should set off some alarm bells in your mind when thinking in a more functional way. There&#8217;s simply no mutable state, since there isn&#8217;t anything like (re-)assignment, hence no destructive updates and also no side effects at all. Just look back at our algebraic datatypes we produced so far. There, we also can&#8217;t mutate a given <em>Shape </em>for example:</p>
<p><pre class="brush: scala;">
sealed abstract class Shape
case class Circle( radius : Double ) extends Shape
case class Rectangle( width : Double, height : Double ) extends Shape
...
val rectangle = Rectangle( width = 5, height = 2 )
val anotherRectangle = Rectangle( 10, 5 )
</pre></p>
<p>Once we created a certain version (or value) of a shape, it stays forever &#8211; just immutable. But how can we ever provide a functional version of a list type which allows for updating their <em>content</em> then? Again, we only need to<a href="http://gleichmann.wordpress.com/2010/10/28/functional-scala-introduction/" target="_blank"> look back</a> at the very basic characteristics of functional programming: all values which ever exist are just &#8230; values (in contrast to variables, which refer to a specific area within memory, which is occupied by a value and might be changed in place). So any operation upon a specific value can only produce or result into another value. For a first grasp, just watch again our well-known friend:</p>
<p><pre class="brush: scala;">
val scale : ( Int, Shape ) =&gt; Shape
    =
    ( times :Int, shape :Shape ) =&gt; shape match {

        case Circle( r ) =&gt; Circle( times * r )
        case Rectangle( w, h ) =&gt; Rectangle( times * w, times * h )
}

val rectangle = Rectangle( 10, 15 )
val anotherRectangle = scale( 2, rectangle )
</pre></p>
<p>Aaahhh, by scaling a shape instance, we didn&#8217;t mutate the given one in place, but produce a new instance, which is kind of <em>derived </em>from the old one. The same should be true for lists: an operation upon a specific <em>list value</em> might result into a new <em>list value</em>. In other words: updating a certain version of a functional list should produce another, new version of a list without destroying the old one! Such functional data structures also got a fancy name, to contrast them from their ephemeral relatives: a (immutable) data structure which supports multiple versions at a time is called a <em>persistent</em> data structure.</p>
<h3>A persistent List structure</h3>
<p>So how could we achieve a persistent list? First of all, the above examples might give us a first hint: in a functional environment, it&#8217;s common to characterize values of a certain type by defining and finally using some value constructors of an algebraic datatype. Now, we need to think hard about the possible structure of a list (or any sequential data structure if you will) and how to represent them as an algebraic datatype. Remember our <a href="http://gleichmann.wordpress.com/2011/03/06/functional-scala-a-little-expression-language-with-algebraic-datatypes-and-pattern-matching/" target="_blank">last</a> <a href="http://gleichmann.wordpress.com/2011/03/13/functional-scala-expressions-extensions-and-extractors/">example</a>, where we introduced a datatype for representing an infinite set of algebraic expressions? There, we defined some value constructors for atoms (our basic building blocks) and operations, which recursively act on sub-expressions. What about a list? Could we also identify some atoms and some recursive structure, say for a list of integers? Maybe there should be a representation for an empty integer list. So let&#8217;s start with that:</p>
<p><pre class="brush: scala;">
sealed abstract class IntList
case object EmptyIntList extends IntList
</pre></p>
<p>Ok, now we&#8217;re able to create an empty integer list, using that singleton case object <em>EmptyIntList</em> as our first value constructor, hurray! Now comes the interesting part. Think of <em>EmptyIntList </em>as the <em>atom </em>of our list type. Like with our arithmetic expressions, can we create another list which uses the empty list just as a component for creating another, new list instance (just like we used two integer literals and created a new instance of an <em>Add </em>expression)? Well, then we might add another value constructor which just takes our empty list (as a representative of an IntList) and another integer value and say that this is a valid list, too. Observe:</p>
<p><pre class="brush: scala;">
sealed abstract class IntList
case object EmptyIntList extends IntList
case class NonEmptyIntList( hd :Int, tl :IntList ) extends IntList
</pre></p>
<p>This second value constructor just takes an arbitrary integer value and an arbitrary, existing list and <em>composes </em>both into a new list instance. If you look carefully at the structure of that value constructor, you might compare the construction of such a list instance to kind of <em>prepending </em>the new integer value to that existing list:</p>
<p><pre class="brush: scala;">
val intList = NonEmptyIntList( 3, NonEmptyIntList( 2, NonEmptyIntList( 1, EmptyIntList ) ) )
...
val anotherIntList = NonEmptyIntList( 4, intList )
</pre></p>
<p>Under this point of view, you might wanna identify the given integer value as the head of the new list and the already existing list as the tail of the new list. Note, that we didn&#8217;t destroyed <em>intList </em>while constructing <em>anotherIntList</em>! It looks like we prepended another integer value to <em>intList</em>, but the original structure stays untouched. We&#8217;ve only used <em>intList </em>to be the tail of that newly constructed list. And since both lists are immutable, we can be very confident that no evil rascal might destroy our list instance. Again, this characteristic also received a snazzy name with which you might swank in front of your team members from now on: ist&#8217;s called <em>structural sharing</em>.</p>
<h3>Going polymorphic</h3>
<p>So far, we&#8217;re only able to produce lists of integer values. If we would like to build another list of say string values, we couldn&#8217;t use our <em>IntList</em>! Because it would be pretty dense to come up with an individual list-like data structure for every type we wanna hold within that list, we might consider another, better solution! In fact, we&#8217;re able to leverage parametric polymorphism again and abstract over the type of the lists content:</p>
<p><pre class="brush: scala;">
sealed abstract class Lst[A]
case class EmptyLst[A] extends Lst[A]
case class Cons[A]( head :A, tail :Lst[A] ) extends Lst[A]
</pre></p>
<p>Aahhh, by introducing parametric polymorphism, we&#8217;re able to produce lists of different types. We just added a type parameter to our new type <em>Lst</em> (remember, it&#8217;s a very simple implementation &#8211; for a full blown list, we&#8217;re going to add that missing i). In that case, our value constructors need to provide that polymorphism and therefore be polymorph in the type of its elements, too (since the concrete type isn&#8217;t chosen until we define a certain list instance). Also note that we&#8217;ve renamed our second value constructor to <em>Cons</em>, as its a widely used name (for <em>cons</em>tructing a new list). Let&#8217;s take a look at building some list instances of different types:</p>
<p><pre class="brush: scala;">
val intList :Lst[Int] = Cons( 1, Cons( 2, Cons( 3, EmptyLst[Int] ) ) )
val stringList = Cons( &quot;a&quot;, Cons( &quot;b&quot;, Cons( &quot;c&quot;, EmptyLst[String] ) ) )
</pre></p>
<p>Hm, anything annoying so far? By adding that type parameter, our list-like data structure become a bit more complex: take a look at our <em>atom</em>, the empty list. We needed to change it from a singleton case object to a case class, in order to provide polymorphism. In that case we also needed to come up with a different instance of an empty list for every individual type of the lists content, e.g. an <em>EmptyLst[Int]</em> and an <em>EmptyLst[String]</em>. Since our data structure is immutable, there&#8217;s really no need to have more than one instance of an empty list (since all lists we ever create might refer to the one and same immutable empty list object as their final tail).</p>
<p>Is there a way to get back to the empty list as a single case object <em>and </em>provide parametric polymorphism? Yes, there is. It turns out that Scala provides a &#8216;special&#8217; type <em>Nothing</em>, which praises itself as the sub-type of all types. Come again? Well, in almost the same manner <em>as Any </em>is the super-type of all types, <em>Nothing </em>can be considered as the sub-type of all types. You build a new type? <em>Nothing </em>is a subtype of it &#8211; it sits always at the bottom of your type hierarchy in Scala. So what should speak against leveraging that fact into our list type, like this:</p>
<p><pre class="brush: scala;">
sealed abstract class Lst[A]
case object EmptyLst extends Lst[Nothing]
case class Cons[A]( head :A, tail :Lst[A] ) extends Lst[A]
</pre></p>
<p>Wow, the compiler seems to be statisfied with that. <em>EmptyLst </em>is again a singleton case object, extending <em>Lst[Nothing]</em>. And since <em>Nothing </em>is the sub-type of all types, so for our yet parametric type <em>A</em>, too. But take a look at the compiler if we now try to come up with a concrete list instance:</p>
<p><pre class="brush: scala;">
val intList = Cons( 1, Cons( 2, Cons( 3, EmptyLst ) ) )
// error: type mismatch; found EmptyLst.type ... required: EmptyLst[Int]
</pre></p>
<p>Hold on, what&#8217;s that? Didn&#8217;t we just say <em>Nothing </em>is the sub-type of all types, so also for type <em>Int</em>? Yep, we did! And that&#8217;s why the compiler didn&#8217;t complain when declaring <em>EmptyLst </em>that way! But what&#8217;s that error message sayin&#8217; then? Well, in this case, we simply didn&#8217;t allow the tail of a list to be of a subtype of <em>A</em> (which is <em>Int</em> in that case) when applying <em>tail </em>to our value constructor <em>Cons</em>. This is due to the fact, that we declared our list type to be <em>invariant </em>in our type parameter <em>A</em> (which i&#8217;m not going to explain in this episode, since there are many good ressources out there explaining type variance in Scala). So what&#8217;s left to do is to declare our type to be covariant in type parameter <em>A</em> and we&#8217;re done:</p>
<p><pre class="brush: scala;">
sealed abstract class Lst[+A]
...
val intList = Cons( 1, Cons( 2, Cons( 3, EmptyLst ) ) )
val stringList = Cons( &quot;a&quot;, Cons( &quot;b&quot;, Cons( &quot;c&quot;, EmptyLst ) ) )
</pre></p>
<p>See that <em>+</em> before our type parameter <em>A</em>? It&#8217;s the sign for telling Scala that our list type will behave covariant in <em>A</em>. Now constructing some list instances with different types &#8211; all refering to our singleton empty list &#8211; shouldn&#8217;t be a problem anymore! Wow, it seems that we&#8217;re now constructed a full blown persistent, polymorphic, recursive, list-like algebraic datatype.</p>
<h3>Summary</h3>
<p>Hey, we did not bad as Tinkerbells! We&#8217;ve just accomplished the first step on our way to understand the deeper meaning and characteristics of persistent list-like data structures! We started with a comparison of ephemeral, destructive data structures (which are widely used in the imperative world) and so called persistent data structures, coming from the functional world! While ephemeral data structures are mutable and therefore change in place over time, a persistent data structure can be seen as an immutable value which might result into another independend value when operating upon the orginial one. The new value might be seen as a consecutive version of the original one, which then co-exist in parallel, maybe exploiting some structural sharing.</p>
<p>On our way to set up an appropriate list type, we saw that parametric polymorphism may be a good option to come up with a single algebraic datatype which abstracts over the type of the lists content. By introducing a type parameter, our list type became a member of what&#8217;s called a type constructor: from now on, we need to give a concrete type (for the lists content) in order to get a proper list instance. That&#8217;s what usually happen when you move from a monomorphic type (like <em>IntList</em>) to a polymorphic type: our <em>Lst</em> type alone isn&#8217;t viable anymore. We first need to do type parametrization in order to get to a full blown type (like <em>Lst[Int]</em>).</p>
<p>We&#8217;re by far not finished yet. What about &#8216;updating&#8217; or &#8216;replacing&#8217; a single element within a given list? What about the concatenation of to lists? Can we still rely on structural sharing? And what about the <em>cost </em>of those operations? Is there a way to put some syntatctic sugar to our list type, say when constructing lists or do pattern matching on them? As these are all valid questions, we&#8217;re going to answer them within the next episode, while also taking a closer look on some basic and more advanced functions on lists. So don&#8217;t be afraid of the frog &#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gleichmann.wordpress.com/752/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gleichmann.wordpress.com/752/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gleichmann.wordpress.com/752/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gleichmann.wordpress.com/752/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gleichmann.wordpress.com/752/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gleichmann.wordpress.com/752/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gleichmann.wordpress.com/752/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gleichmann.wordpress.com/752/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gleichmann.wordpress.com/752/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gleichmann.wordpress.com/752/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gleichmann.wordpress.com/752/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gleichmann.wordpress.com/752/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gleichmann.wordpress.com/752/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gleichmann.wordpress.com/752/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=752&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gleichmann.wordpress.com/2011/03/20/functional-scala-tinkerbell-frogs-and-lists/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/19bad137a600728b7cfeadace9b561fb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mario.gleichmann</media:title>
		</media:content>
	</item>
		<item>
		<title>Functional Scala: Expressions, Extensions and Extractors</title>
		<link>http://gleichmann.wordpress.com/2011/03/13/functional-scala-expressions-extensions-and-extractors/</link>
		<comments>http://gleichmann.wordpress.com/2011/03/13/functional-scala-expressions-extensions-and-extractors/#comments</comments>
		<pubDate>Sun, 13 Mar 2011 18:01:19 +0000</pubDate>
		<dc:creator>Mario Gleichmann</dc:creator>
				<category><![CDATA[general]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://gleichmann.wordpress.com/?p=711</guid>
		<description><![CDATA[Welcome back to another episode of Functional Scala. This one is the sequel to our extended sample on representing and resolving arithmetic expressions using algebraic datatypes and pattern matching. In this second part i try to answer a legitimate question: what are the advantages and disadvantages of algebraic datatypes (consisting of pure data, no behaviour), [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=711&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Welcome back to another episode of Functional Scala.</p>
<p>This one is the sequel to <a href="http://gleichmann.wordpress.com/2011/03/06/functional-scala-a-little-expression-language-with-algebraic-datatypes-and-pattern-matching/" target="_blank">our extended sample</a> on representing and resolving arithmetic expressions using algebraic datatypes and pattern matching. In this second part i try to answer a legitimate question: what are the advantages and disadvantages of algebraic datatypes (consisting of pure data, no behaviour), espacially if we wanna expand our expression language  &#8211; and what&#8217;s that all to do with the visitor pattern?<span id="more-711"></span></p>
<p>The expansion of our expression language might come in two flavors: on the one hand we might add some new functionality (for most of us are highly influenced by an object oriented paradigm, let&#8217;s call it behaviour), like simplifying arbitrary expressions before evaluating them. On the other hand, we might wanna extend the building blocks of our expression language itself, like mixing in some more operations or adding some variables beside our integer literals.</p>
<h3>Extending functionality</h3>
<p>First, let&#8217;s see how easy it is to add some new functionality. You may remember our function <em>reduce </em>(and with it function <em>resolve </em>for a stepwise reduction of an arbitrary expression). Let&#8217;s repeat that again, using a rather complex expression:</p>
<p><pre class="brush: scala;">
val expr = Mult(
            Sub(Literal(6), Mult(Sub( Literal(5), Literal(3)), Literal(3))),
            Add(Literal(3), Mult(Literal(5), Literal(8))))

for( e &lt;- resolve( expr ) ) println( format( e ) )

// will print ...
// ( ( 6 - ( ( 5 - 3 ) * 3 ) ) * ( 3 + ( 5 * 8 ) ) )
// ( ( 6 - ( 2 * 3 ) ) * ( 3 + ( 5 * 8 ) ) )
// ( ( 6 - 6 ) * ( 3 + ( 5 * 8 ) ) )
// ( 0 * ( 3 + ( 5 * 8 ) ) )
// ( 0 * ( 3 + 40 ) )
// ( 0 * 43 )
// 0
</pre></p>
<p>Now take a closer look at line 11. While the first sub-expression&#8217;s already evaluated to zero, we still continue to reduce the second sub-expression, only to discover that the whole expression comes down to zero finally. Let&#8217;s say that executing a single reduction step (and with it the evaluation of a basic expression) is real expensive. What we need is a way to simplify a given expression, if we detect some trivial <em>patterns </em>which let us skip further reduction (like multiplying an arbitrary expression with zero finally results in zero). In other words, let&#8217;s add that functionality. Going the functional way by using algebraic datatypes and pattern matching, this is a rather easy task: we don&#8217;t need to touch the different building blocks of our language, but simply add another function which scans for some trivial patterns to reduce:</p>
<p><pre class="brush: scala;">
val simplify : Expression =&gt; Expression
    =
    ( expr :Expression) =&gt; expr match {

        case Add( Literal(0), expr ) =&gt; expr
        case Add( expr, Literal(0) ) =&gt; expr
        case Add( left, right ) =&gt; Add( simplify( left ), simplify( right ) )

        case Mult( Literal(0), _ ) =&gt; Literal(0)
        case Mult( _, Literal(0) ) =&gt; Literal(0)
        case Mult( Literal(1), expr ) =&gt; expr
        case Mult( expr, Literal(1) ) =&gt; expr
        case Mult( left, right ) =&gt; Mult( simplify( left ), simplify( right ) )

        case Sub( Literal(x), Literal(y) ) if x == y =&gt; Literal(0)
        case Sub( left, right ) =&gt; Sub( simplify( left ), simplify( right ) )

        case _ =&gt; expr
}
</pre></p>
<p>Ok, in order to make use of those simplifications, we need to adapt our function <em>reduce</em>. We could do that in a way of just composing those two functions:</p>
<p><pre class="brush: scala;">
val simplifiedReduce = ( expr :Expression ) =&gt; reduce( simplify( expr ) )
</pre></p>
<p>This works fine while calling our new function directly. But what about our function <em>stepResolve</em>, which still calls <em>reduce </em>directly? Well, in this case we just won the silver medal. We might need to adapt <em>stepResolve</em> and all other functions which might also rely on <em>resolve</em>, which clearly violates open closed principle! So another option left would be to adapt function <em>resolve </em>directly:</p>
<p><pre class="brush: scala;">
val reduce : Expression =&gt; Expression
    =
    ( expr :Expression ) =&gt; simplify( expr ) match {

        case Literal(_) =&gt; expr
        ...
}
</pre></p>
<p>Ahhh, ok &#8211; before we&#8217;re going to pattern match, we just simplify the given expression. Everything ok? If we did pattern matching the right way, everything would be fine. But take a closer look at line 5. Do you spot the risk? This will result in a nice but nevertheless endless recursion when doing stepwise reduction! Again, watch what we&#8217;re returning in that case. It&#8217;s the original expression, not the simplified one! So while simplification results into a literal, the original expression might be a more complex, nested one. And since we return the original expression, stepwise reduction wouldn&#8217;t stop. So is there a possible escape? of course! Everything would be fine, if we just return the literal, we were matching against. Observe:</p>
<p><pre class="brush: scala;">
val reduce : Expression =&gt; Expression
    =
    ( expr :Expression ) =&gt; simplify( expr ) match {

        case lit @ Literal(_) =&gt; lit
        ...
}
</pre></p>
<p>Wow, that was easy again. If we don&#8217;t rely on the given functions argument (that is <em>expr</em>) but instead stay <em>local </em>and only refer to those elements we&#8217;re matching against (that is <em>lit</em>) we&#8217;re free to transform the ingoing value in every which way we want while not compromising pattern matching!</p>
<p>With our adapted function at hand , let&#8217;s see if we can save some reduction steps:</p>
<p><pre class="brush: scala;">
val expr = Mult(
            Sub(Literal(6), Mult(Sub( Literal(5), Literal(3)), Literal(3))),
            Add(Literal(3), Mult(Literal(5), Literal(8))))

for( e &lt;- resolve( expr ) ) println( format( e ) )

// will print ...
// ( ( 6 - ( ( 5 - 3 ) * 3 ) ) * ( 3 + ( 5 * 8 ) ) )
// ( ( 6 - ( 2 * 3 ) ) * ( 3 + ( 5 * 8 ) ) )
// ( ( 6 - 6 ) * ( 3 + ( 5 * 8 ) ) )
// ( 0 * ( 3 + ( 5 * 8 ) ) )
// 0
</pre></p>
<p>Well, it seems that we in fact saved some reduction steps! Praise to simplification!</p>
<h3>Extending data</h3>
<p>While we have seen, that it&#8217;s relatively easy to extend functionality by more or less adding some new functions, let&#8217;s see how easy it is to extensd our language itself. Say we wanna add another binary operation, like a modulo operation. First we need to extend our algebraic datatype:</p>
<p><pre class="brush: scala;">
sealed abstract case class Expression
...
case class Mod( x :Expression, y :Expression ) extends Expression
</pre></p>
<p>Now this was the easy part! What about our functions which are build upon our language blocks? For example, let&#8217;s take a closer look at our function <em>eval</em>. Since we declared our datatype as <em>sealed</em>, the compiler has the chance to detect all possible value constructors and see if we&#8217;ve matched against all possible cases. In this situation, the compiler complains that our <em>match is not exhaustive! missing combination Mod</em>! So let&#8217;s give what he deserves:</p>
<p><pre class="brush: scala;">
val eval : Expression =&gt; Int
    =
    _ match {
        ...
        case Mod( leftExpr, rightExpr ) =&gt; eval( leftExpr ) % eval( rightExpr )
}
</pre></p>
<p>It turns out, that possibly <em>every</em> function, which is based on our language needs to be adapted! So we can&#8217;t stop with <em>eval</em>, but also need to consider <em>reduce</em>, <em>simplify </em>(if we detect some patterns for simplifying expressions, based on modulo) , <em>format </em>and so on. This may become really ugly! For example let&#8217;s take a look at a rather worst case scenario: let&#8217;s focus on function <em>reduce</em>! There, we might add a whole bulk of new case expressions for every new operation:</p>
<p><pre class="brush: scala;">
val reduce : Expression =&gt; Expression
    =
    ( expr :Expression ) =&gt; simplify( expr ) match {

        case lit @ Literal( _ ) =&gt; lit

        case Add( Literal(_), Literal(_) ) =&gt; Literal( eval(expr) )
        case Add( left @ Literal(_), rightExpr ) =&gt; Add( left, reduce( rightExpr ) )
        case Add( leftExpr, right @ Literal(_) ) =&gt; Add( reduce( leftExpr ), right )
        case Add( leftExpr, rightExpr ) =&gt; Add( reduce( leftExpr ), rightExpr )

        // case Sub ... cases omitted

        // case Mult ... cases omitted

        case Mod( Literal(_), Literal(_) ) =&gt; Literal( eval(expr) )
        case Mod( left @ Literal(_), rightExpr ) =&gt; Mod( left, reduce( rightExpr ) )
        case Mod( leftExpr, right @ Literal(_) ) =&gt; Mod( reduce( leftExpr ), right )
        case Mod( leftExpr, rightExpr ) =&gt; Mod( reduce( leftExpr ), rightExpr )
}
</pre></p>
<p>Oh my god! Such functions gets bigger and bigger with every new binary operation we&#8217;re going to add to our expression language! If we take a closer look to those case expressions for <em>Add </em>and those case Expressions for <em>Mod </em>(as also to those for <em>Sub </em>and <em>Mult</em>) we can clearly see some similarities: in fact we could abstract away from the concrete binary operation and concentrate on the reduction of its operands in a rather <em>polymorph</em> way.</p>
<h3>One Extractor to match them all</h3>
<p>Unfortunately we need to match against those different value constructors! Well, do we really need to? It turns out, that Scala provides the idea of a so called Extractor, which gives some kind of independence when it comes to pattern matching. You can think of an Extractor as a way to <em>deconstruct </em>a given value in an arbitrary way, not determined by the structure of your datatype. This is all done by a simple method <em>unapply</em> which takes a value of any type and returns an Option, containing a tuple for the single parts which gets revealed by the process of deconstruction. On the other side, we&#8217;re allowed to simply return None as a way to show that we can&#8217;t deconstruct a given value &#8211; in this case, there won&#8217;t be a successful match! Sounds confusing? All gets better with a simple example. Just watch:</p>
<p><pre class="brush: scala;">
object BinaryOp{

    def unapply( x :Any ): Option[ Tuple2[Expression,Expression] ] = {

        x match{

            case Add( l, r ) =&gt; Some( ( l, r ) )
            case Sub( l, r ) =&gt; Some( ( l, r ) )
            case Mult( l, r ) =&gt; Some( ( l, r ) )
            case Mod( l, r ) =&gt; Some( ( l, r ) )
            case _ =&gt; None
        }
    }
}
</pre></p>
<p>Our first Exctractor! As said, it&#8217;s simply an object with a single method <em>unapply</em>, taking any value and resulting in an Option of an arbitrary tuple. In our case, we try to match the given value against all known binary operations. If we get a match, we simply return the left and right operand of the given operator. Otherwise we just return None, showing that the given value can&#8217;t be deconstructed into the operations operands. With our new Extractor at hand, we might happily try to give a more concise, <em>polymorph</em> implementation for our function <em>reduce</em>:</p>
<p><pre class="brush: scala;">
val reduce : Expression =&gt; Expression
    =
    ( expr : Expression ) =&gt;  simplify( expr ) match {

        case lit @ Literal( _ ) =&gt; lit

        case BinaryOp( left @ Literal(_), right @ Literal(_) ) =&gt; Literal( eval( ??? ) )

        case BinaryOp( left @ Literal(_), rightExpr ) =&gt; ???( left, reduce( rightExpr ) )
        ...
}
</pre></p>
<p>Uhm, what started so promising turns out to be useless, since we also need to refer to (or to know at least) the concrete operation on the right side of our case expressions! So this is a dead end? Hm, what prevents us to return the operation as a whole within our Extractor, too? Nothing? Then let&#8217;s extend it:</p>
<p><pre class="brush: scala;">
object BinaryOp{

    def unapply( x: Any ): Option[ Tuple3[Expression,Expression,Expression] ] = {

        x match{

            case add @ Add( l, r ) =&gt; Some( ( add, l, r ) )
            case sub @ Sub( l, r ) =&gt; Some( ( sub, l, r ) )
            case mult @ Mult( l, r ) =&gt; Some( ( mult, l, r ) )
            case mod @ Mod( l, r ) =&gt; Some( ( mod, l, r ) )
            case _ =&gt; None
        }
    }
}
</pre></p>
<p>Aahhh, now we&#8217;re able to also refer to the operation as a whole! But wait a minute. This is just not enough. Sometimes, we need to construct a new operator value on the right side of a case expression which will carry some reduced argument (like at line 9 of our new implementation for <em>reduce</em>). But since we&#8217;re able to refer to the old operator, we can think of a function, which just constructs a new operation based on a given one and some operands. You might think of it as a kind of a <em>factory function</em>:</p>
<p><pre class="brush: scala;">
val construct : (Expression, Expression, Expression ) =&gt; Expression
    =
    ( op :Expression, fst :Expression, snd :Expression ) =&gt; op match {

        case a :Add =&gt; Add( fst, snd )
        case s :Sub =&gt; Sub( fst, snd )
        case m :Mult =&gt; Mult( fst, snd )
        case mo :Mod =&gt; Mod( fst, snd )
}
</pre></p>
<p>There you go! We just leveraged another mechanism for doing pattern matching in Scala. This time we just matched the given operation expression against its <em>type</em>. Since Scala is also an object oriented language, everything is an object (during runtime) in Scala. And while every object belongs to a type, so values of our datatype, too.</p>
<p>Now that we&#8217;ve got all ingredients to write some new functions in a more <em>polymorphic </em>way, let&#8217;s see how to do with our function under focus:</p>
<p><pre class="brush: scala;">
val reduce : Expression =&gt; Expression
    =
    ( expr : Expression ) =&gt;  simplify( expr ) match {

        case lit @ Literal( _ ) =&gt; lit
        case BinaryOp( binOp,  left @ Literal(_), right @ Literal(_) ) =&gt; Literal( eval( binOp ) )
        case BinaryOp( binOp, left @ Literal(_), rightExpr ) =&gt; construct( binOp, left, reduce( rightExpr ) )
        case BinaryOp( binOp, leftExpr, right @ Literal(_) ) =&gt; construct( binOp, reduce( leftExpr ), right )
        case BinaryOp( binOp, leftExpr, rightExpr ) =&gt; construct( binOp, reduce( leftExpr ), rightExpr )
}
</pre></p>
<p>That&#8217;s all! Our function shrinked to only 5 cases. We never need to touch it again when adding some new binary operations. Of course we need to extend <em>eval </em>and <em>construct </em>with every new operation, but that&#8217;s all left to do. All other functions based on operations of our little expression language might stay stable, as long as they operate on a more abstract level (that is not need to act upon a concrete operation)! Take a look at this example, were i added another operation <em>Pow </em>(for power) and only extended our Extractor <em>BinOp </em>plus functions <em>eval </em>and <em>build</em>:</p>
<p><pre class="brush: scala;">
val expr = Mult(
            Add(Literal(6),Mult(Sub(Literal(5),Mod(Literal(5),Add(Literal(2),Literal(1)))),Literal(3))),
            Add(Literal(3),Mult(Pow(Sub(Literal(10),Literal(6)),Literal(5)),Literal(8))))

for( e &lt;- resolve( expr ) ) println( format( e ) )

// will print ...
// ( ( 6 + ( ( 5 - ( 5 % ( 2 + 1 ) ) ) * 3 ) ) * ( 3 + ( ( ( 10 - 6 ) ^ 5 ) * 8 ) ) )
// ( ( 6 + ( ( 5 - ( 5 % 3 ) ) * 3 ) ) * ( 3 + ( ( ( 10 - 6 ) ^ 5 ) * 8 ) ) )
// ( ( 6 + ( ( 5 - 2 ) * 3 ) ) * ( 3 + ( ( ( 10 - 6 ) ^ 5 ) * 8 ) ) )
// ( ( 6 + ( 3 * 3 ) ) * ( 3 + ( ( ( 10 - 6 ) ^ 5 ) * 8 ) ) )
// ( ( 6 + 9 ) * ( 3 + ( ( ( 10 - 6 ) ^ 5 ) * 8 ) ) )
// ( 15 * ( 3 + ( ( ( 10 - 6 ) ^ 5 ) * 8 ) ) )
// ( 15 * ( 3 + ( ( 4 ^ 5 ) * 8 ) ) )
// ( 15 * ( 3 + ( 1024 * 8 ) ) )
// ( 15 * ( 3 + 8192 ) )
// ( 15 * 8195 )
// 122925
</pre></p>
<p>Now that we extended our operations, is it also possible to extend the atoms within our language? Until now, we can only express some integer literals, making the whole expression kind of static.</p>
<h3>Let&#8217;s be variable &#8230;</h3>
<p>What about introducing a variable as another atom? It could look like this:</p>
<p><pre class="brush: scala;">
sealed abstract class Expression
...
case class Var( x :String ) extends Expression
</pre></p>
<p>Hurray! We&#8217;re just added the possibility to also note some variable parts within our expressions. We simply state a variable and give&#8217;em a name:</p>
<p><pre class="brush: scala;">
val expr = Mult(
            Add( Literal( 6 ), Mult( Sub( Var( &quot;x&quot; ), Literal( 3 ) ), Literal( 3 ) ) ),
            Add( Literal( 3 ), Mult( Literal( 5 ),  Var( &quot;y&quot; ) )  ) )
</pre></p>
<p>Wow, that looks really good! But ask yourself what the result of e.g. <em>Mult( Literal( 5 ),  Var( &#8220;y&#8221; ) )</em> may be? Well, in order to resolve such an expression, we need to extend our model in a more fundamental way: along with the expression, we also need an <em>environment</em>, which delivers a concrete integer value for every variable. Let&#8217;s first define what we understand under an <em>environment </em>and how we could deliver a certain value from of a given environment (for a given variable name):</p>
<p><pre class="brush: scala;">
type Environment = List[ ( String, Int ) ]

val lookup : ( String, Environment ) =&gt; Int
    =
    (  Key :String, env :Environment ) =&gt; env match {

        case Nil =&gt; 0
        case ( Key, i ) :: _  =&gt; i
        case  _ :: xs =&gt; lookup( Key, xs )
}
</pre></p>
<p>Wowowow! Now that needs a little bit of explanation, don&#8217;t you think? First we just give a <em>description </em>of what we understand of an environment. It&#8217;s just a type alias for a list of pairs, where each pair consist of a String value (which might be interpreted as our variable name) and an integer value (which might be consisdered as the value to substitude for a given variable). We also could have used another data structure called <em>Map</em>, but we just wanna restrict ourself to some core data structures here!</p>
<p>Next is our function <em>lookup</em>, which takes a String (let&#8217;s say a variable name for which we&#8217;re interested in the related integer value) and an environment and results into an integer value. So far, we&#8217;ve cheated a little bit: in case there is an empty environment (that is, we can&#8217;t substitude a variable name), we simply return zero (we&#8217;ll use an Option for such cases in the near future, so don&#8217;t be worried). The second case expression tries to match the first (head) pair of the environments list against the given Key. If we have a match, we can deliver the assigned integer value. Did you note the first letter of our given key is in upper case? That&#8217;s because Scala interprets a name solely in lower cases within a pattern as a variable name (to bind the deconstructed, revealed part of the given pattern). That&#8217;s not what we want here! We wanna match against a concrete value &#8211; that&#8217;s the <em>Key</em>, given as the functions first argument.</p>
<p>Since the introduction of variables is such a fundamental extension (also forcing the introducing of an environment to substitute variables by an integer value), we also need to adapt our functions. For evaluating an arbitrary expression, we now also need a certain environment in order to resolve some variables within it:</p>
<p><pre class="brush: scala;">
val eval : (Expression, Environment) =&gt; Int
    =
    (exp :Expression, env: Environment) =&gt; simplify ( exp ) match {

        case lit @ Literal( x ) =&gt; lit
        case Var( x ) =&gt; lookup( x, env )
        case Add( leftExpr, rightExpr ) =&gt; eval( leftExpr, env ) + eval( rightExpr, env )
        case Mult( leftExpr, rightExpr ) =&gt; eval( leftExpr, env ) * eval( rightExpr, env )
        case Sub( leftExpr, rightExpr ) =&gt; eval( leftExpr, env ) - eval( rightExpr, env )
        case Mod( leftExpr, rightExpr ) =&gt; eval( leftExpr, env ) % eval( rightExpr, env )
}
</pre></p>
<p>But that&#8217;s not enough! Let&#8217;s get back to our worst case function <em>reduce</em>. Similarly to our binary operations, we also might want do handle atoms in a more <em>polymorphic </em>way (that is to act on literals and variables in the same way without differentiating between them). Wait a minute. Didn&#8217;t we discovered a way to pattern match on a datatype without relying on their real structure? Yeah, extractors to the rescue, again!</p>
<p><pre class="brush: scala;">
object Atom{

    def unapply( x: Any ): Option[Expression] = {

        x match{

            case literal @ Literal(_) =&gt; Some( literal )
            case variable @ Var(_) =&gt; Some( variable )
            case _ =&gt; None
        }
    }
}
</pre></p>
<p>Aaahhh, we only have a match if there&#8217;s a literal or a variable. Only in this two cases, we return an expression, which is just the found literal or atom. In all other cases we&#8217;ll return None, so there will be no match in an arbitrary case expression. Now we can adapt <em>reduce </em>like so:</p>
<p><pre class="brush: scala;">
val reduce : ( Expression, Environment) =&gt; Expression
    =
    ( exp : Expression, env :Environment ) =&gt; simplify( exp ) match {

        case Atom( variable @ Var(_) ) =&gt; Literal( eval( variable, env ) )
        case Atom( a ) =&gt; a
        case BinaryOp( binOp, Atom(variable @ Var(_)), rightExpr ) =&gt; construct( binOp, reduce( variable,env ), rightExpr )
        case BinaryOp( binOp, leftExpr, Atom(variable @ Var(_)) ) =&gt; construct( binOp, leftExpr, reduce( variable, env ) )
        case BinaryOp( binOp, Atom(_), Atom(_) ) =&gt; Literal( eval( binOp, env ) )
        case BinaryOp( binOp, left @ Atom(_), rightExpr ) =&gt; construct( binOp, left, reduce( rightExpr, env ) )
        case BinaryOp( binOp, leftExpr, right @ Atom(_) ) =&gt; construct( binOp, reduce( leftExpr, env  ), right )
        case BinaryOp( binOp, leftExpr, rightExpr ) =&gt; construct( binOp, reduce( leftExpr, env ), rightExpr )
}
</pre></p>
<p>Ok, let&#8217;s inspect that function. We see that it&#8217;s possible to use pattern binding even within a pattern declared by extractors. Take a look at lines 5, 7 and 8 for example: there we wanna be sure that the atom <em>really is</em> a variable so we can transform it into an equivalent integer literal just by evaluating the variable to it&#8217;s value. There are other cases (e.g. line 9, 10 and 11) where we&#8217;re not interested in the concrete form of that atom. There, we only wanna be sure that the operands are just arbitrary atoms, so we don&#8217;t need to reduce them any more! There also, you might have seen, that we&#8217;re allowed to nest some patterns using multiple extractors: we simply used the <em>BinaryOp </em>pattern to extract the operator and its operands while matching against an arbitrary operator. Now within the extracted parts (so within the <em>BinaryOp </em>pattern) we additionally match the extracted operands against another extractor pattern <em>Atom</em>.</p>
<p>Now it&#8217;s time to try our extended language. We could have a single expression featuring some variables and provide multiple environments for assigning variables in some diffeent ways:</p>
<p><pre class="brush: scala;">
val expr = Mult(
            Add( Literal( 6 ), Mult( Sub( Var( &quot;x&quot; ), Literal( 3 ) ), Literal( 3 ) ) ),
            Add( Literal( 3 ), Mult( Literal( 5 ),  Var( &quot;y&quot; ) )  ) )

for( exp &lt;- resolve( expr,  ( &quot;y&quot;, 8 ) :: ( &quot;x&quot;, 1) :: Nil ) )  println( format( exp ) )

// will print
// ( ( 6 + ( ( x - 3 ) * 3 ) ) * ( 3 + ( 5 * y ) ) )
// ( ( 6 + ( ( 1 - 3 ) * 3 ) ) * ( 3 + ( 5 * y ) ) )
// ( ( 6 + ( -2 * 3 ) ) * ( 3 + ( 5 * y ) ) )
// ( ( 6 + -6 ) * ( 3 + ( 5 * y ) ) )
// ( 0 * ( 3 + ( 5 * y ) ) )
// 0
...

for( exp &lt;- resolve( expr1_2,  ( &quot;y&quot;, 42 ) :: ( &quot;x&quot;, 17 ) :: Nil ) ){ println( format( exp ) ) }

// will print
// ( ( 6 + ( ( x - 3 ) * 3 ) ) * ( 3 + ( 5 * y ) ) )
// ( ( 6 + ( ( 17 - 3 ) * 3 ) ) * ( 3 + ( 5 * y ) ) )
// ( ( 6 + ( 14 * 3 ) ) * ( 3 + ( 5 * y ) ) )
// ( ( 6 + 42 ) * ( 3 + ( 5 * y ) ) )
// ( 48 * ( 3 + ( 5 * y ) ) )
// ( 48 * ( 3 + ( 5 * 42 ) ) )
// ( 48 * ( 3 + 210 ) )
// ( 48 * 213 )
// 10224
</pre></p>
<p>Works like a charm! We <em>only </em>needed to touch almost every function &#8230;</p>
<h3>Summary</h3>
<p>Whew! What a journey! We&#8217;re at the end of our extended example. Most of the given data and functionality are based on two concepts: algebraic datatypes and pattern matching. We almost saw every possible way to do pattern matching in Scala: we pattern matched against the natural structure of some case classes (which we leveraged as a kind of description for some value constructors of an algebraic datatype) and deconstructed their nested components, using variable binding, wildcards (remember the underscore) or some concrete values. We pattern matched against some <em>artificial </em>patterns, provided by some custom extractors. We matched against types and used variables to bind whole or part of some patterns.</p>
<p>We saw that pattern matching is a more easy task when adding some new functionality while the number of value constructors for our datatype remains stable. This way you might wanna compare the whole construct to the visitor pattern. There also, you may have a number of (non subtype-polymorphic) types where you need to define a certain functionality upon a composite structure for some nested values of those types. The visitor will also kind of <em>deconstruct </em>the given nested structure while visiting each node. You can see each <em>visit </em>method as a kind of case expression which gets called if the visitor hits a value of the right kind.</p>
<p>Like with the visitor pattern, it&#8217;s more easy to add new visitors (providing another functionality), but it&#8217;s extremely inconvenient if you add some new types. This would mean that you need to <em>visit </em>and adapt each existing visitor implementation, adding another <em>visit </em>method to handle the new type!</p>
<p>The same is true for algebraic datatypes and pattern matching. If your datatype appears to be very fragile, then it may be the wrong choice, since you also need to potentially update all your functions based on that datatype. You might soften that pain by introducing some custom extractors to kind of abstract over some of your value constructors! If your datatype remains more stable on the other side, pattern matching might be an elegant way to add some new functionality over time. Only it provides some more options for using different patterns and pattern semantics at your own neeed (while a visitor might only match against a certain type). I hope you&#8217;ve seen some of its flexibility within the last two episodes &#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gleichmann.wordpress.com/711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gleichmann.wordpress.com/711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gleichmann.wordpress.com/711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gleichmann.wordpress.com/711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gleichmann.wordpress.com/711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gleichmann.wordpress.com/711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gleichmann.wordpress.com/711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gleichmann.wordpress.com/711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gleichmann.wordpress.com/711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gleichmann.wordpress.com/711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gleichmann.wordpress.com/711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gleichmann.wordpress.com/711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gleichmann.wordpress.com/711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gleichmann.wordpress.com/711/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=711&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gleichmann.wordpress.com/2011/03/13/functional-scala-expressions-extensions-and-extractors/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/19bad137a600728b7cfeadace9b561fb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mario.gleichmann</media:title>
		</media:content>
	</item>
		<item>
		<title>Functional Scala: a little expression language with algebraic datatypes and pattern matching</title>
		<link>http://gleichmann.wordpress.com/2011/03/06/functional-scala-a-little-expression-language-with-algebraic-datatypes-and-pattern-matching/</link>
		<comments>http://gleichmann.wordpress.com/2011/03/06/functional-scala-a-little-expression-language-with-algebraic-datatypes-and-pattern-matching/#comments</comments>
		<pubDate>Sun, 06 Mar 2011 19:56:14 +0000</pubDate>
		<dc:creator>Mario Gleichmann</dc:creator>
				<category><![CDATA[general]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://gleichmann.wordpress.com/?p=680</guid>
		<description><![CDATA[Welcome to another episode of Functional Scala! In this episode we&#8217;ll going to recap and employ everything we&#8217;ve learned so far about algebraic datatypes and pattern matching for implementing a more extensive example. We&#8217;ll put all those little pieces together which we&#8217;ve discovered so far and see how they work in cooperation for building a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=680&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Welcome to another episode of Functional Scala!</p>
<p>In this episode we&#8217;ll going to recap and employ everything we&#8217;ve learned so far about algebraic datatypes and pattern matching for implementing a more extensive example. We&#8217;ll put all those little pieces together which we&#8217;ve discovered so far and see how they work in cooperation for building a little language which allows us to write, pretty print, step-wise reduce and evaluate arbitrary arithmetic expressions (considering addition, subtraction and multiplication on integer values). And as the cherry on top, we&#8217;ll discover some new flavour of algebraic datatypes and pattern matching.<span id="more-680"></span></p>
<p>It may be a good start to first give some thoughts on how we wanna represent algebraic expressions. Just consider a language of expressions build up from basic values (integer literals) and some operations on them (e.g. addition or multiplication of some integer values). For example, the following are all arithmetic expressions:</p>
<p style="padding-left:10px;">17</p>
<p style="padding-left:10px;">17 + 23</p>
<p style="padding-left:10px;">109 * ( 8 + 15 )</p>
<p>An expression in its simplest form might be an integer literal. That&#8217;s a legal expression for sure! And how could we represent such an entity within our little language? What about an algebraic datatype <em>Expression</em>? Right, mate! Good idea! Let&#8217;s write it down:</p>
<p><pre class="brush: scala;">
sealed abstract case class Expression
case class Literal( x :Int ) extends Expression
</pre></p>
<p>Ok, so far we have a simple and neat product type, since we could express a whole bunch of different integer literals, just using that single value constructor:</p>
<p><pre class="brush: scala;">
val expr1 = Literal( 1 )
val expr2 = Literal( 17 )
...
val exprN = Literal( 532 )
</pre></p>
<p>Well, if you think that&#8217;s boring, you&#8217;re again right! So far, our Expressions are a bit too simple, right? How do you feel about adding some operations which will take some integer literals and act on them? The addition of two integer literals surely pose an Expression in itself. So let&#8217;s add it as another value constructor to our datatype, extending our expression language:</p>
<p><pre class="brush: scala;">
sealed abstract case class Expression
case class Literal( x :Int ) extends Expression
case class Add( a :Literal, b :Literal ) extends Expression
</pre></p>
<p>Aaahh, now things start to become more interesting. Our new value constructor also features some components, that is two integer literals which act as the operands for our operation <em>Add</em>.</p>
<p><pre class="brush: scala;">
val sum1 = Add( Literal( 17 ), Literal( 4 ) )
val sum2 = Add( Literal( 123 ), Literal( 321 )
</pre></p>
<p>In a sense, we&#8217;ve just created a recursive datatype (ok, indirectly), since those two components are also Expressions! Um, wait a minute! What was that? Those two components are also expressions? Yep, we just declared literals as being legal Expressions in its simplest form! But is there actually any reason why we restrict addition to act on integer literals directly? If we would allow arbitrary Expressions as operands, we could express nested Expressions within our language like this:</p>
<p><pre class="brush: scala;">
val sum3 = Add( Literal( 21 ), Add( Literal( 17 ), Literal( 4 ) ) )
val sum4 = Add(  Add( Literal( 19 ), Literal( 2 ) ), Literal( 12 ) )
</pre></p>
<p>In fact, there&#8217;s nothing to be said against nested operations (unless you want to restrict yourself to ordinary, basic expressions). From this point of view, we could build arbitrary nested expressions in a recursive way. This recursice nature of building expressions is directly reflected within our value constructors! Observe:</p>
<p><pre class="brush: scala;">
sealed abstract case class Expression
case class Literal( x :Int ) extends Expression
case class Add( x :Expression, y :Expression ) extends Expression
case class Mult( x :Expression, y :Expression ) extends Expression
case class Sub(  x :Expression, y :Expression ) extends Expression
</pre></p>
<p>See the recurive structure? We now defined an algebraic datatype with a recursive structure, allowing us to build arbitrary nested arithmetic expressions. Since there are several operations all acting on an arbitrary expression, we could mix them in every which way.</p>
<p><pre class="brush: scala;">
val expr1 =  Mult( Literal( 6 ), Add( Literal( 3 ), Literal( 4 )  ) )
val expr2 = Sub(Mult(Literal(21), Add(Literal(103), Literal(42))), Add(Literal(17), Mult(Literal(29), Literal(7))))
val expr3 = Mult(Sub(Literal(6), Mult(Sub( Literal(5), Literal(3)), Literal(3))), Add(Literal(3), Mult(Literal(5), Literal(8))))
</pre></p>
<p>Ah, ok! We&#8217;re now able to construct arbitrary expressions featuring any level of nesting, so we could come up with some rather complex expressions. Hm, is there anything annoying?</p>
<h3>A pretty printer</h3>
<p>At least, we might got some problems when trying to read a more complex expression. It&#8217;s rather difficult to detect the correct nesting structure, resulting from the fact that operations are expressed in postfix notation within our little language. For that to change, let&#8217;s write a little function which takes an arbitrary expression and results into a string which represents the given expression in infix notation (which our brain is trained to scan and recognize).</p>
<p>Given the recursive nature of our expressions, we can mirror that fact directly within our function: we&#8217;ll pattern match against every possible value constructor for our <em>Expression </em>type, formatting them into their related infix format and than filling the gaps for every sub-expression (that are the operands for any given operation) by just formatting them recursively. Just watch:</p>
<p><pre class="brush: scala;">
val format : Expression =&gt; String
    =
    _ match {
        case Literal( x ) =&gt; x.toString
        case Add( leftExpr, rightExpr ) =&gt; &quot;( &quot; + format( leftExpr ) + &quot; + &quot; + format( rightExpr ) + &quot; )&quot;
        case Mult( leftExpr, rightExpr ) =&gt; &quot;( &quot; + format( leftExpr ) + &quot; * &quot; + format( rightExpr ) + &quot; )&quot;
        case Sub( leftExpr, rightExpr ) =&gt; &quot;( &quot; + format( leftExpr ) + &quot; - &quot; + format( rightExpr ) + &quot; )&quot;
}
</pre></p>
<p>That&#8217;s all? Aye, mate! That&#8217;s all! We&#8217;ve just looked at every basic expression type and give an appropriate format. By binding the components for the value constructors of any given operation, we referred to them at the right side of a case expression being able to format them recursively before inserting them into their right place within the string representation for the current operation. This way we&#8217;re now able to pretty print any given expression, like the ones above:</p>
<p><pre class="brush: scala;">
println( format( expr1 ) )  // ( 6 * ( 3 + 4 ) )
println( format( expr2 ) )  // ( ( 21 * ( 103 + 42 ) ) - ( 17 + ( 29 * 7 ) ) )
println( format( expr3 ) )  // ( ( 6 - ( ( 5 - 3 ) * 3 ) ) * ( 3 + ( 5 * 8 ) ) )
</pre></p>
<p>Ok, now we got a weapon for printing any given expression in infix notation, no matter how complex (read deeply nested) they may be.</p>
<h3>Evaluation</h3>
<p>What about evaluating a given expression? Finally, we might wanna resolve a complex expression down to a single integer value by evaluating all operations within that expression. Is this any harder as formatting a nested expression? Surely not! It turns out that we can rely on the very same recursive nature of our datatype! So while evaluating a single operation, we just evaluate the value for every operand recursively, again.</p>
<p><pre class="brush: scala;">
val eval : Expression =&gt; Int
    =
    _ match {
        case Literal( x ) =&gt; x
        case Add( leftExpr, rightExpr ) =&gt; eval( leftExpr ) + eval( rightExpr )
        case Mult( leftExpr, rightExpr ) =&gt; eval( leftExpr ) * eval( rightExpr )
        case Sub( leftExpr, rightExpr ) =&gt; eval( leftExpr ) - eval( rightExpr )
}

</pre></p>
<p>See the structural similarity to our function <em>format</em>, which&#8217;s again reflecting the structural similarity to our recursive datatype? Anyhow, now we can just apply any expression to our <em>eval </em>function and receive the final, resolved integer value, to which the expression evaluates:</p>
<p><pre class="brush: scala;">
eval( expr1 )  // 42
eval( expr2 )  // 2825
eval( expr3 )  // 0
</pre></p>
<p>Wow, our last expression evaluated to zero! Did you see that coming? Well, it would be nice if we had a function which could reduce a given expression step-wise, so that we could follow the single resolvement steps until we finally receive a single integer literal.</p>
<h3>Step by step, oh baby &#8230;</h3>
<p>For this to realize, we need to find a plan which <em>expression patterns</em> we&#8217;re able to reduce in which way. Surely, a given integer literal can&#8217;t be reduced any further. What&#8217;s about the addition of two literals? Well, we only could reduce it to a single integer literal, illustrating the result of that basic addition. As soon as their&#8217;s at least one more complex (nested) operand, we first need to reduce that operand solely, before reducing the whole operation in a next step. I think you got the idea: we just need to act on every operation in exactly the same way:</p>
<p><pre class="brush: scala;">
val reduce : Expression =&gt; Expression
    =
    ( expr :Expression ) =&gt; expr match {

        case Literal(_) =&gt; expr

        case Add( Literal(_), Literal(_) ) =&gt; Literal( eval( expr ) )
        case Add( left @ Literal(_), rightExpr ) =&gt; Add( left, reduce( rightExpr ) )
        case Add( leftExpr, right @ Literal(_) ) =&gt; Add( reduce( leftExpr ), right )
        case Add( leftExpr, rightExpr ) =&gt; Add( reduce( leftExpr ), rightExpr )

        case Sub( Literal(_), Literal(_) ) =&gt; Literal( eval( expr ) )
        case Sub( left @ Literal(_), rightExpr ) =&gt; Sub( left, reduce( rightExpr ) )
        case Sub( leftExpr, right @ Literal(_) ) =&gt; Sub( reduce( leftExpr ), right )
        case Sub( leftExpr, rightExpr ) =&gt; Sub( reduce( leftExpr ), rightExpr )

        case Mult( Literal(_), Literal(_) ) =&gt; Literal( eval( expr ) )
        case Mult( left @ Literal(_), rightExpr ) =&gt; Mult( left, reduce( rightExpr ) )
        case Mult( leftExpr, right @ Literal(_) ) =&gt; Mult( reduce( leftExpr ), right )
        case Mult( leftExpr, rightExpr ) =&gt; Mult( reduce( leftExpr ), rightExpr )
}
</pre></p>
<p>Wowowow, hold on! What&#8217;s going on here? Everything looks familiar for the first case expression: there, we simply match the given expression against a single literal. We&#8217;re not interested in the given integer value for that literal (therefore the underscore), since we only return the given expression back in case of a match. Same goes for the first case expression matching against <em>Add</em>: since both operands mark some simple integer literals, we&#8217;ll return a new literal which represents the sum (by addition) of those two basic operands.</p>
<p>No need to get scared of the next case expression. There we wanna match against <em>Add </em>while the first operand being a simple literal and the second one a nested expression (we know that the second operand can&#8217;t be a literal &#8211; in that case there would&#8217;ve been a match on the first case for <em>Add</em>, right?). If we got a match &#8211; hence a literal for the first and a nested expression for the second operand &#8211; we&#8217;ll return a <em>new (!) Add </em>expression, were the second operand is going to be reduced and the first operand just remains the same. Now we got a dilemma: we needed to match the first operand against a literal pattern while also refering to it as a whole on the right side for building a new <em>Add </em>expression! But specifying a literal pattern prevents us to declare a variable binding for the first operand. And the other way round, if we simply declare a variable binding for the first operand, how can we be sure to match against a literal pattern simultaneously?</p>
<p>That&#8217;s the moment our new constsuct &#8211; the @-annotation &#8211; is waiting for! It&#8217;s just a way to bind a variable to a pattern! So in our case, we just match the first operand against a literal pattern and bind that whole pattern (that is the first operand, in case you&#8217;ve forgot it) to a variable named <em>left</em>. So if there&#8217;s a match, we have a convenient way to refer to the first operand on the right side while it&#8217;s guaranteed to be a simple literal.</p>
<p>Now it&#8217;s time to see our new function in action. Let&#8217;s take a rather complex expression and reduce it step by step:</p>
<p><pre class="brush: scala;">
val expr1 = Mult(Sub(Literal(6), Mult(Sub( Literal(5), Literal(3)), Literal(3))), Add(Literal(3), Mult(Literal(5), Literal(8))))

val expr2 = reduce( expr1 )
val expr3 = reduce( expr2 )
val expr4 = reduce( expr3 )
val expr5 = reduce( expr4 )
val expr6 = reduce( expr5 )
val expr7 = reduce( expr6 )

println( format( expr1 ) )  // ( ( 6 - ( ( 5 - 3 ) * 3 ) ) * ( 3 + ( 5 * 8 ) ) )
println( format( expr2 ) )  // ( ( 6 - ( 2 * 3 ) ) * ( 3 + ( 5 * 8 ) ) )
println( format( expr3 ) )  // ( ( 6 - 6 ) * ( 3 + ( 5 * 8 ) ) )
println( format( expr4 ) )  // ( 0 * ( 3 + ( 5 * 8 ) ) )
println( format( expr5 ) )  // ( 0 * ( 3 + 40 ) )
println( format( expr6 ) )  // ( 0 * 43 )
println( format( expr7 ) )  // 0
</pre></p>
<p>There you go. Now we&#8217;ve received a better understanding on how the whole expression&#8217;s evaluating to zero. We&#8217;ve kind of <em>debugged </em>the resolvement process, watching every intermediate step. Too bad, we need two know the number of steps in advance! So why not write a function which takes an expression and results into a list of expressions which represent the intermediate expressions after each reduction step until we reach a single literal:</p>
<p><pre class="brush: scala;">
val stepResolve : ( Expression,List[Expression] ) =&gt; List[Expression]
    =
    ( expr :Expression, steps :List[Expression] ) =&gt; expr match {

        case Literal(_) =&gt; expr :: steps
        case _ =&gt; stepResolve( reduce( expr ), expr :: steps )
}
</pre></p>
<p>Experts that we are, we can easily see what&#8217;s going on: the function just takes an expression and a list of expressions and then just acts on the given expression. If it&#8217;s a simple literal (the base case) then we can&#8217;t reduce the expression any further. We just prepend the expression to the list of expressions and be done. Otherwise we&#8217;re also prepending the expression but need to reduce it at least one more time. For our conveniance, we could come up with another function which just take a single expression and then starts the recursive resolvement steps just by providing an empty list at the start:</p>
<p><pre class="brush: scala;">
val resolve  =  ( expr :Expression ) =&gt; stepResolve( expr, Nil ).reverse
</pre></p>
<p>So if you apply the above expression <em>expr1 </em>to <em>resolve</em>, you gonna receive all intermediate expressions, starting with the given expression down to the final integer literal:</p>
<p><pre class="brush: scala;">
for( expr &lt;- resolve( expr1 ) ) println( format( expr ) )

// will print ...
// ( ( 6 - ( ( 5 - 3 ) * 3 ) ) * ( 3 + ( 5 * 8 ) ) )
// ( ( 6 - ( 2 * 3 ) ) * ( 3 + ( 5 * 8 ) ) )
// ( ( 6 - 6 ) * ( 3 + ( 5 * 8 ) ) )
// ( 0 * ( 3 + ( 5 * 8 ) ) )
// ( 0 * ( 3 + 40 ) )
// ( 0 * 43 )
// 0
</pre></p>
<h3>Summary</h3>
<p>In this episode we saw algebraic datatypes and pattern matching in practice. We used both to implement a little language for building representations of arbitrary nested arithmetic expressions and operate on them. We recognized <em>Expression </em>as a recursive datatype, since operational expressions like <em>Add </em>or <em>Mult </em>may take some other Expressions as their operands, which is directly reflected by their corresponding value constructors.</p>
<p>In addition to that, most of our functions also reflected the recursice nature of such an expression in a similar way: they were matching against those different value constructors to handle each expression type individually while operating recursively on the operands for any given operation. There we discovered @-annotations which gives us a way to match against a pattern and bind that pattern to a variable for further reference.</p>
<p>We&#8217;re not at the end of our road, considering arithmetic expressions. As you&#8217;ve seen while debugging through the intermediate expressions during the single resolvement steps, we did some more needless reduction steps. Since the first operand of a multiplication was already zero, we still did some reduction steps on the right operand yet. We&#8217;ll see in the next episode how we could get rid of those unnecessary steps by applying some trivial simplifications to our expressions. In addition to that, we&#8217;ll see how to reduce the number of case expression within our function <em>reduce</em>. In both cases, we&#8217;re going to discover some yet unknown forms of pattern matching and will encounter a way for kind of creating your own patterns, leveraging so called extractors. Hope to see you then &#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gleichmann.wordpress.com/680/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gleichmann.wordpress.com/680/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gleichmann.wordpress.com/680/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gleichmann.wordpress.com/680/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gleichmann.wordpress.com/680/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gleichmann.wordpress.com/680/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gleichmann.wordpress.com/680/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gleichmann.wordpress.com/680/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gleichmann.wordpress.com/680/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gleichmann.wordpress.com/680/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gleichmann.wordpress.com/680/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gleichmann.wordpress.com/680/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gleichmann.wordpress.com/680/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gleichmann.wordpress.com/680/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=680&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gleichmann.wordpress.com/2011/03/06/functional-scala-a-little-expression-language-with-algebraic-datatypes-and-pattern-matching/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/19bad137a600728b7cfeadace9b561fb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mario.gleichmann</media:title>
		</media:content>
	</item>
		<item>
		<title>Functional Scala: Pattern Matching on product types</title>
		<link>http://gleichmann.wordpress.com/2011/02/27/functional-scala-pattern-matching-on-product-types/</link>
		<comments>http://gleichmann.wordpress.com/2011/02/27/functional-scala-pattern-matching-on-product-types/#comments</comments>
		<pubDate>Sun, 27 Feb 2011 23:09:48 +0000</pubDate>
		<dc:creator>Mario Gleichmann</dc:creator>
				<category><![CDATA[general]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://gleichmann.wordpress.com/?p=655</guid>
		<description><![CDATA[Welcome to another episode of Functional Scala! This time, we&#8217;ll finally discover how to pattern match on product types. Within the last episodes we saw how to use pattern matching on some rather simple sum types. The one question left is how to use pattern matching and therein refer to the single components of a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=655&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Welcome to another episode of Functional Scala!</p>
<p>This time, we&#8217;ll finally discover how to pattern match on <a href="http://gleichmann.wordpress.com/2011/02/05/functional-scala-algebraic-datatypes-sum-and-product-types/" target="_blank">product types</a>. Within the last episodes we saw how to use pattern matching on some rather simple sum types. The one question left is how to use pattern matching and therein refer to the single components of a given value constructor for a product type.</p>
<p>So let&#8217;s start right away with a little warm-up and revisit our well known product type <em>Shape</em>. To make things a bit more interesting, let&#8217;s add <em>Triangle </em>(considered right-angled for simplicity sake) as another value constructor. Here it comes:<span id="more-655"></span></p>
<p><pre class="brush: scala;">
slealed abstract class Shape
case class Circle( radius : Double ) extends Shape
case class Rectangle( width : Double, height : Double ) extends Shape
case class Triangle( base : Double, height : Double ) extends Shape
</pre></p>
<p>Ok, ok, nothing new so far. Now, let&#8217;s define a new function which returns the area for any given value of a Shape. Ring, Ring &#8211; is there a way of applying pattern matching? Of course! We could give a separate case expression for every individual Shape. So let&#8217;s match against the different value constructors, like we did before with sum types! Uhm, err, but what about the fields? No matter &#8211; as we said, let&#8217;s simply match against the value constructors. As soon as they offer some fields, we only need to <em>mimic</em> those within our pattern: if we wanna refer to them afterwards, we can simply bind them by providing a free variable name on the right position within our value constructor pattern. Observe:</p>
<p><pre class="brush: scala;">
import sala.Math.{Pi,pow}

val area : Shape =&gt; Double
    =  _ match {
    case Circle( radius ) =&gt; Pi * ( pow( radius, 2.0 ) )
    case Rectangle( width, height ) =&gt; width * height
    case Triangle( base, height ) =&gt; height * base / 2
}
</pre></p>
<p>Ah, ok now things gettin&#8217; clearer, right? We simply applied some variable names for every single field within our individual value constructors, se we refer to them afterwards on the right side of each case expression for calculating the right area. See that variable <em>radius </em>within the first case expression for matching against circles. This one is a free variable name and only accidentally named after the same name used within the original value constructor. You could use whatever (free) variable name you want, as long as they start with a lower case (that&#8217;s the sign for Scala to bind the fields value from the actual Shape instance to that variable).</p>
<p>Of course you&#8217;re not forced to always bind your fields to a variable. Say we wanna add some optimization and directly return the height of a Rectangle, if the width is 1 (and vice verca). There, we could simply add another case expression just <em>before </em>our common case for Rectangles (otherwise we would always match against the common case):</p>
<p><pre class="brush: scala;">
...
case Rectangle( 1, height ) =&gt; height
case Rectangle( width, 1 ) =&gt; width
case Rectangle( width, height =&gt; width * height
...
</pre></p>
<p>See that we&#8217;re also allowed to match single fields of a certain value constructor against a constant value. And what about our friend, the underscore? It&#8217;s of course valid syntax to place them at the position of arbitrary fields. Now guess its meaning &#8211; again, we apply the underscore if we simply don&#8217;t care about the fields value. If we wanna give an own case expression for the more or less unlikely case of a Triangle with a base of zero, we wouldn&#8217;t be interested about the value of its height at all. Check it out:</p>
<p><pre class="brush: scala;">
...
case Triangle( 0, _ ) | Triangle( _, 0 ) =&gt; 0
case Triangle( base, height ) =&gt; height * base * 2
...
</pre></p>
<p>Nothing to be scared! We just said that if the first or second field is of value 0, then we dont care about the companion field (by placing an underscore at its position)  because the whole case expression evaluates to zero anyway.</p>
<h3>A little brick world</h3>
<p>Let&#8217;s just concentrate on rectangles for the rest of this episode and create some more functions to play with them. Say we wanna use them to build a little brick world where you can topple or stack them. For a first glance, let&#8217;s write a function which takes a rectangle and returns another rectangle where width and height is just switched. Experts that we are now, easy as it can be:</p>
<p><pre class="brush: scala;">
val switch : Rectangle =&gt; Rectangle
    =  _ match {
    case Rectangle( w, h ) =&gt; Rectangle( h, w )
}
</pre></p>
<p>A tiny little Function. It does nothing more then using pattern matching to kind of <em>unwrap </em>the components of that product types value constructor. Now you see why pattern matching is sometimes named as <em>deconstruction</em>: a value constructor (like <em>Rectangle</em>) constructs a new value from some given values for its individual components (that is the fields for <em>width </em>and <em>height</em>) while pattern matching deconstructs that value again and kind of unveils the individual components.</p>
<p>Now imagine we wanna stack two rectangles. The result might be another, new <em>Shape </em>called <em>Stack </em>(i know, it&#8217;s no real Shape, but think it&#8217;s for the sake of easy continuation for this episode). So let&#8217;s just add it:</p>
<p><pre class="brush: scala;">
...
case class Stack( top :Rectangle, bottom :Rectangle ) extends Shape
...
val myStack = Stack( Rectangle( 5, 10 ), Rectangle( 7, 12 ) )
</pre></p>
<p>Ok, so with this new Shape on board, we could build some new stacks simply by taking two rectangles and use our new value constructor. Let&#8217;s say we want to make our stacks a little more robust by trying to pile them in a more controlled way: whenever two sides of a rectangle are of the same length, we use those sides to stack them. Means that we may switch a given rectangle if the length of its height corresponds with the length of the companions width and vice verca!</p>
<h3>A Guard for stacking</h3>
<p>So far so good! But how can we pattern match under regard of some conditions? Of course we could do some kind of case analysis on the right side of an case expression which may lead to nested pattern matching. You may try it and judge for yourself if such functions remain well structured and readable. Fortunately pattern matching offers something called <em>Guards</em>, which is nothing more (but also nothing less) as a kind of Predicate which also need to be fulfilled in order to have a valid match. In Scala, a guard is simply a boolean expression, preceded by keyword <em>if</em>. Just watch:</p>
<p><pre class="brush: scala;">
val stack : ( Rectangle, Rectangle ) =&gt; Stack
    =
    ( r1 : Rectangle, r2 : Rectangle ) =&gt; ( r1, r2 ) match {
        case( Rectangle( w1,_ ), Rectangle( w2,_ ) ) if w1 == w2 =&gt; Stack( r1, r2 )
        case( Rectangle( w1,_ ), Rectangle( _,h2 ) ) if w1 == h2 =&gt; stack( r1, switch( r2 ) )
        case( Rectangle( _,h1 ), Rectangle( w2,_ ) ) if h1 == w2 =&gt; stack( switch( r1 ), r2 )
	case _ =&gt; Stack( r1, r2 )
}
</pre></p>
<p>As you can see, we just added a guard to our pattern. As soon as the basic pattern matches, the guard is evaluated. If the guard results to <em>true</em>, we have a final  match, If the guard results to <em>false</em>, we haven&#8217;t a match and pattern matching will continue with the next case expression.</p>
<h3>Summary</h3>
<p>This time, we just saw that pattern matching on product types is not more complicated than we already saw with sum types. The only additional feature is to provide some meaningful expressions for a product types components (that are the fields of a given value constructor.)</p>
<p>As we saw, we could simply put a new variable at the position of a field, which binds the fields current value to that variable (so we can use it at the right side of the case expression). This way we can <em>deconstruct </em>a value of a given product type back into its individual parts. If we&#8217;re not interested in some of those parts we simply use the almighty underscore (again) at those positions.</p>
<p>Another way of pattern match was to just apply constant values for some or all components of a product type. This way we could match against some individual cases were we&#8217;re just fixing some components. We used that in order to fish for some special cases which needed some special treatment (e.g. for the sake of performance).</p>
<p>Finally, we saw a first simple use case for guards. As we&#8217;ll see, this is a very powerful mechanism to incorporate some conditions into our patterns. With guards we can not only match against a static pattern, but also put some additional <em>dynamic </em>relations to a pattern, which can&#8217;t be directly expressed by only looking at a types fields. We will make some more use of guards in the next episode, where we&#8217;ll discover some recursive defined datatypes and tryin&#8217; to pattern match against. In addition to that, we&#8217;ll see some yet undiscovered techniques offered by Scalas pattern matching mechanism, which will even inrease its range of application. Stay tuned &#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gleichmann.wordpress.com/655/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gleichmann.wordpress.com/655/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gleichmann.wordpress.com/655/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gleichmann.wordpress.com/655/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gleichmann.wordpress.com/655/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gleichmann.wordpress.com/655/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gleichmann.wordpress.com/655/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gleichmann.wordpress.com/655/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gleichmann.wordpress.com/655/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gleichmann.wordpress.com/655/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gleichmann.wordpress.com/655/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gleichmann.wordpress.com/655/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gleichmann.wordpress.com/655/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gleichmann.wordpress.com/655/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=655&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gleichmann.wordpress.com/2011/02/27/functional-scala-pattern-matching-on-product-types/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/19bad137a600728b7cfeadace9b561fb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mario.gleichmann</media:title>
		</media:content>
	</item>
		<item>
		<title>Functional Scala: Combinatoric Pattern Matching</title>
		<link>http://gleichmann.wordpress.com/2011/02/20/functional-scala-combinatoric-pattern-matching/</link>
		<comments>http://gleichmann.wordpress.com/2011/02/20/functional-scala-combinatoric-pattern-matching/#comments</comments>
		<pubDate>Sun, 20 Feb 2011 19:57:24 +0000</pubDate>
		<dc:creator>Mario Gleichmann</dc:creator>
				<category><![CDATA[general]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://gleichmann.wordpress.com/?p=636</guid>
		<description><![CDATA[Welcome to another episode of functional Scala! In the last episode we were introducing ourself to the idea of Pattern matching &#8211; a powerful mechanism for operating on algebraic datatypes by examining different occurrences for a certain type separately, each within an individual case expression. So far, we only matched single values of some sum [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=636&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Welcome to another episode of functional Scala!</p>
<p>In the <a href="http://gleichmann.wordpress.com/2011/02/13/functional-scala-pattern-matching-the-basics/" target="_blank">last episode</a> we were introducing ourself to the idea of Pattern matching &#8211; a powerful mechanism for operating on algebraic datatypes by examining different occurrences for a certain type separately, each within an individual case expression. So far, we only matched single values of some sum types by their given value constructors. In this episode we&#8217;re going to see how to match against a combination of sum type values.<span id="more-636"></span></p>
<p>As threatened in the last episode, imagine we need some tri-state logic for implementing a simple probabilistic model. In this model, we wanna be able to resolve some propositions to be either <em>true </em>or <em>false </em>or &#8216;<em>maybe true or false</em>&#8216; (we don&#8217;t know yet). Don&#8217;t you think this calls for an own datatype? There might be three different values, say <em>True</em>, <em>False </em>and <em>Maybe</em>. Let&#8217;s give <em>Maybe </em>some special honor: because it looks some kind of exceptional in relation to those well known others, we might name our new datatype <em>Moolean</em>. So let&#8217;s not lose any further word and first define an appropriate datatype:</p>
<p><pre class="brush: scala;">
sealed abstract class Moolean
case object True extends Moolean
case object False extends Moolean
case object Maybe extends Moolean
</pre></p>
<p>So far, this is all boring. What we have here is a simple, pure sum type, featuring three value constructors. Now things get more interesting, if we want to write some methods which operate on them. What about some pure moolean functions, which solely combine or transform some given moolean values. For a warm-up, we could implement a function <em>not</em>, which kind of <em>inverts </em>a given moolean value:</p>
<p><pre class="brush: scala;">
val not : Moolean =&gt; Moolean
    =
    ( mool :Moolean ) =&gt; mool match {
        case True =&gt; False
        case False =&gt; True
        case Maybe =&gt; Maybe
    }
</pre></p>
<p>Ahhh, it all seems familiar for <em>True </em>and <em>False</em>: we just behave like their <em>Boolean </em>counterpart. Inversing <em>Maybe </em>results into <em>Maybe </em>in our modell. Think like &#8216;<em>Maybe true</em>&#8216; gets inverted into &#8216;<em>Maybe false</em>&#8216; and also the other way round. Either way, it remains a <em>Maybe</em>. Now this is busines as usual. We just give a separate case expression for every possible value constructor, catching all possible cases for our given value <em>mool</em>.</p>
<p>Whats about combining two moolean values? Let&#8217;s say we wanna implement an own function <em>equals </em>which takes two moolean values and decides if they both are of the same value constructor. Let&#8217;s pretend there isn&#8217;t such a comparison for free in Scalas case classes, so we need to implement it on our own. Now, putting ourself in that difficult position, we now have to answer the question how to match against two moolean values simultaneously, since we need to match against both values within our case expressions in order to decide equality. After a short while you may get to the solution to simply express both values as a simple (ad hoc) pair and simply match against that instance of <em>Tuple2 </em>(which is a product type, by the way&#8230;). Observe:</p>
<p><pre class="brush: scala;">
val equal : ( Moolean, Moolean ) =&gt; Moolean
    =
    ( a :Moolean, b :Moolean ) =&gt; ( a, b ) match {
        case ( True, True ) =&gt; True
        case ( False, False ) =&gt; True
        case ( Maybe, Maybe ) =&gt; True
        case _ =&gt; False
    }
</pre></p>
<p>Ok, seems we can always put those individual values into a tuple and then match against that tuple! See how we could easily absorb all cases where both values aren&#8217;t of the same value constructor? Instead of factoring out all possible combinations, we just gathered them within our <em>otherwise </em>case.</p>
<p>Combining more than one value now gives rise for another nice application of the underscore: you can use&#8217;em not only as the all and final otherwise case, but also for merging only some different cases into one. Sounds funny? All i say is to use the underscore for some values within your tuple combination, where you don&#8217;t care about some values at all. For this to make clear, let&#8217;s say we wanna have a function <em>and</em>, which combines two moolean values in a conjunctive way. And the rules are as follows:</p>
<ol>
<li>as soon as any of the two values is <em>False</em>, the whole expression evaluates to <em>False</em></li>
<li>as soon as any of the two values is <em>Maybe</em>, the whole expression evaluates to <em>Maybe</em></li>
<li>in all other cases, the whole expression evaluates to <em>True</em></li>
</ol>
<p>Note, that the order of evaluation is important. So rule 1 need to be evaluated before rule 2. And because rule 2 is going to be evaluated before rule 3, the only case for rule 3 is to match against two values of <em>True</em>. Fortunately, pattern matching plays into our hands, since the case expressions will be evaluated from top to bottom. See that &#8216;<em>any of the two values</em>&#8216; within our rules? As soon as there is one of both values matched, we really don&#8217;t care about the other one. This can be expressed like so:</p>
<p><pre class="brush: scala;">
val and : ( Moolean, Moolean ) =&gt; Moolean
    =
    ( a :Moolean, b :Moolean ) =&gt; ( a, b ) match {
        case ( False, _ ) =&gt; False
        case ( _, False ) =&gt; False
        case ( Maybe, _ ) =&gt; Maybe
        case ( _, Maybe ) =&gt; Maybe
        case _ =&gt; True
    }
</pre></p>
<p>Aaah, see the first case expression for example? There, we don&#8217;t care if the second value might be <em>True</em>, <em>False </em>or <em>Maybe </em>at all. As soon as the first value matches <em>False</em>, the whole expression evaluates to <em>False</em>. So in this case, we <em>merged </em>three cases into one. You may see the first two cases as somewhat related (just as the third and fourth case as well). They are somewhat the same, we only match against different positions within our tuple. Well, if this disturbs your eyes, or your feelings of elegance at all, you may bring them together into one single case expression, using disjunction:</p>
<p><pre class="brush: scala;">
val or : ( Moolean, Moolean ) =&gt; Moolean
    =
    ( a :Moolean, b: Moolean ) =&gt; ( a, b ) match {
        case ( True, _ ) | ( _, True ) =&gt; True
        case ( Maybe, _ ) | ( _, Maybe ) =&gt; Maybe
        case _ =&gt; False
    }
</pre></p>
<p>Condensing case expressions by disjunction makes your function even more concise. For the first case expression, we just catched all cases now, where the first <em>or </em>the second value&#8217;s matching <em>True</em>.</p>
<h3>A simple Quarternary-Operator</h3>
<p>If you come from Javaland, you surely have heard of the Ternary-Operator. It goes something like this:</p>
<p><pre class="brush: java;">
int absoluteOfA = a &gt; 0 ? a : -1 * a
String yesNo = (true &amp;&amp; (false || true ) ? &quot;yes&quot; : &quot;no&quot;
Order order = selection.equals( &quot;sell&quot; ) ? new SellOrder() : new BuyOrder()
</pre></p>
<p>The ternary-Operator can be seen as an espression, which evaluates to one of two values of a certain type. The value is selected by a boolean expression, which preludes the whole <em>ternary-expression</em> (before the question mark). If the boolean expression evaluates to true, the whole expression evaluates to the first value (or expression) after the question mark, otherwise to the next expression (after the colon).</p>
<p>Because this episode would be to short otherwise, let&#8217;s see how to craft a Quarternary-Operator which evalueates to an arbitrary value of an arbitrary type , depending on a single moolean value. In this case, we not only need to state two values which gets selected depending if the moolean value (or expression which evaluates to a moolean value) is <em>True </em>or <em>False</em>. In addition to that, we need to give a third value which gets selected if the moolean expression evaluates to <em>Maybe</em>. Well, if you can&#8217;t imagine, here&#8217;s a little preview on how we would like our Quaternary-Operator to work:</p>
<p><pre class="brush: scala;">
val shouldBeTrue :String = True ? &quot;TRUE&quot; | &quot;FALSE&quot; | &quot;MAYBE&quot;
val shouldBeZero :Int = Maybe ? 1 | -1 | 0
val shouldBePupil : Person = False ? new Teacher | new Pupil | new Padawan
</pre></p>
<p>Please note, that the following solution will only take values for the three cases. We&#8217;ll see shortly (when looking at lazy evaluation) how to enhance this version for also working with expressions which evaluate to a certain value, only if selected by the preluding moolean value. For our Quarternary-Operator to work in the above drafted way, we need to leverage Scalas feature of implicit type conversion (which i&#8217;m just going to use here without any further explanation) while still relying on pure datatypes (without featuring any methods). We&#8217;re catching any moolean value by an implicit conversion, which starts a series of Quaternary-Fragments. Such a fragment will lead to the next fragment, until the whole expression is constructed. In this case, the expression can be evaluated (by pattern matching), resulting in the value which is given for the current moolean value. Just watch:</p>
<p><pre class="brush: scala;">
implicit def startQuarternary( mool : Moolean ) = new QuarternaryTrueReceiver( mool )

class QuarternaryTrueReceiver[+A]( mool : Moolean ){
    def ?[A]( trueValue :A ) = new QuarternaryFalseReceive( mool, trueValue )
}

class QuarternaryFalseReceiver[+A]( mool : Moolean, trueValue :A ){
    def |[B &gt;: A]( falseValue :B ) = new QuarternaryMaybeReceiver( mool, trueValue, falseValue )
}

class QuarternaryMaybeReceiver[+A]( mool :Moolean, trueValue :A, falseValue :A ){
    def |[B &gt;: A]( maybeValue :B ) = mool match {
        case True =&gt; trueValue
        case False =&gt; falseValue
        case Maybe =&gt; maybeValue
    }
}
</pre></p>
<p>See what&#8217;s going on? Whenever we try to call a method <em>?</em> on a moolean value, implicit type conversion kicks in an calls our method <em>startQuarternary</em>. This method simply starts the chain of producing our fragments in form of separate classes which just collect the individual parts of the whole quarternary-expression. In the last Fragment <em>QuarternaryMaybeReceiver</em>, we&#8217;ve collected all necessary parts, so that we can pattern match against the inducing moolean expression and pick one of the given values to return.</p>
<h3>Summary</h3>
<p>In this episode, we saw how to pattern match against a combination of values &#8211; in our case two values of type Moolean. Of course, those values needn&#8217;t to be of the same type. You might pattern match against every combination of values of arbitrary algebraic datatypes. All is fine, as long as you put them into an appropriate tuple and than match against that tuple.</p>
<p>Further on, we saw how to kind of <em>merge </em>more than one case into one case expression. This we could achieve by &#8211; once again &#8211; applying the underscore (as a kind of placeholder) to those positions within the tuple, we&#8217;re not care about the concrete value. Another way of consolidating more than one case was to bring them together under one case expression in a disjunctive way.</p>
<p>Finally we crafted our own Quarternary-Operator. As you&#8217;ve seen, you&#8217;re kind of able to write your own <em>control structures</em> by need. Our algebraic datatype remained untouched. Instead we used implicit type conversion to start a chain for collecting the different parts of the whole expression.</p>
<p>Still, we only saw how pattern matching can help to structure your functions in a well-arranged way for sum types, yet. By cleverly leveraging the evaluation order of case expressions and merging different cases into one case expression we might gain very concise functions. What&#8217;s still open is operating on product types (well, we already have seen one example in this episode, which kind of sneaked in!). There, we may also need to pattern match against some values which are composed within other datatypes. That will be the topic of the next episode. Looking forward to see you again &#8230;</p>
<div id="_mcePaste" class="mcePaste" style="position:absolute;left:-10000px;top:0;width:1px;height:1px;overflow:hidden;"><strong>As threatened</strong></div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gleichmann.wordpress.com/636/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gleichmann.wordpress.com/636/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gleichmann.wordpress.com/636/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gleichmann.wordpress.com/636/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/gleichmann.wordpress.com/636/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/gleichmann.wordpress.com/636/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/gleichmann.wordpress.com/636/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/gleichmann.wordpress.com/636/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gleichmann.wordpress.com/636/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gleichmann.wordpress.com/636/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gleichmann.wordpress.com/636/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gleichmann.wordpress.com/636/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gleichmann.wordpress.com/636/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gleichmann.wordpress.com/636/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&amp;blog=2165876&amp;post=636&amp;subd=gleichmann&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gleichmann.wordpress.com/2011/02/20/functional-scala-combinatoric-pattern-matching/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/19bad137a600728b7cfeadace9b561fb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mario.gleichmann</media:title>
		</media:content>
	</item>
	</channel>
</rss>
