<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-6373963829340632529</id><updated>2012-01-25T11:51:17.620-02:00</updated><category term='currying'/><category term='scala'/><category term='case class'/><category term='tuples'/><category term='type class'/><category term='programming'/><category term='manifest'/><category term='continuations'/><category term='sbt'/><category term='language'/><category term='scala 2.10'/><category term='collection'/><category term='puzzle'/><category term='algorithm'/><category term='scala 2.9'/><category term='fibonacci'/><category term='equality'/><category term='style'/><category term='outsourcing'/><category term='regex'/><category term='apl'/><category term='scalable-series'/><category term='agile'/><category term='matrix'/><category term='software'/><category term='type erasure'/><category term='projection'/><category term='linux ubuntu boot grub'/><category term='software-engineering'/><category term='rewritting'/><category term='operators'/><category term='parser'/><category term='architecture'/><category term='beginner'/><category term='compiler'/><title type='text'>Algorithmically challenged</title><subtitle type='html'>Random thoughts of an IT worker in the stone age of computer science.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>55</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-370427441742826755</id><published>2012-01-23T18:18:00.000-02:00</published><updated>2012-01-23T18:38:41.971-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='scala 2.10'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>String Interpolation on Scala 2.10</title><content type='html'>One of the &lt;a href="http://docs.scala-lang.org/sips/" target="_blank"&gt;Scala Improvement Proposals&lt;/a&gt; for Scala 2.10 is &lt;a href="http://docs.scala-lang.org/sips/pending/string-interpolation.html" target="_blank"&gt;String Interpolation&lt;/a&gt;. It has recently been added to trunk, behind the &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;-Xexperimental&lt;/span&gt; flag, and I have started playing with it. At first, I stumbled upon bugs and limitations of its current implementation relative to the proposal, but I finally got something working.&lt;br /&gt;&lt;br /&gt;To be clear: the interpolation works fine, in both of the provided forms (with and without formatting). As usual with Scala, it's the possibility of replicating the functionality for my own purposes that gets me excited. I usually explain the whys and the hows of my code, but in this case a simple paste says it all, imho.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;dcs@ayanami:~/github/scala (master)$ scala -Xexperimental&lt;br /&gt;Welcome to Scala version 2.10.0.rdev-4232-2012-01-23-g9a20086 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_26).&lt;br /&gt;Type in expressions to have them evaluated.&lt;br /&gt;Type :help for more information.&lt;br /&gt;&lt;br /&gt;scala&gt; case class StringContext(parts: String*) {&lt;br /&gt;     |   object matching {&lt;br /&gt;     |     def unapplySeq(s: String): Option[Seq[String]] = {&lt;br /&gt;     |       val re = (parts map ("\\Q" + _ + "\\E") mkString ("^", "(.*?)", "$")).r&lt;br /&gt;     |       re findFirstMatchIn s map (_.subgroups)&lt;br /&gt;     |     }&lt;br /&gt;     |   }&lt;br /&gt;     |   def s(args: Any*) = scala.StringContext(parts: _*).s(args: _*)&lt;br /&gt;     | }&lt;br /&gt;defined class StringContext&lt;br /&gt;&lt;br /&gt;scala&gt; "23/01/2012" match { case matching"$day/$month/$year" =&gt; s"$month-$day-$year" }&lt;br /&gt;res0: String = 01-23-2012&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-370427441742826755?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/370427441742826755/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2012/01/string-interpolation-on-scala-210.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/370427441742826755'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/370427441742826755'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2012/01/string-interpolation-on-scala-210.html' title='String Interpolation on Scala 2.10'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-2495407794211942342</id><published>2012-01-09T21:50:00.001-02:00</published><updated>2012-01-10T02:57:29.986-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Adding methods to Scala Collections</title><content type='html'>&lt;span style="font-family: inherit;"&gt;I don't like getting much involved in these Scala flame wars, but &lt;a href="http://yz.mit.edu/wp/true-scala-complexity/" target="_blank"&gt;this recent article&lt;/a&gt;&amp;nbsp;left me a bit irked. At some point, the following statement is made:&lt;/span&gt;&lt;br /&gt;&lt;div&gt;&lt;span style="font-family: inherit;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;&lt;span style="font-family: inherit;"&gt;"&lt;span style="background-color: white; border-bottom-width: 0px; border-color: initial; border-image: initial; border-left-width: 0px; border-right-width: 0px; border-style: initial; border-top-width: 0px; color: #373737; line-height: 24px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px; outline-color: initial; outline-style: initial; outline-width: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; vertical-align: baseline;"&gt;it is impossible to insert a new method that behaves like a normal collection method&lt;/span&gt;&lt;span style="background-color: white; color: #373737; line-height: 24px;"&gt;. "&lt;/span&gt;&lt;/span&gt;&lt;/i&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;&lt;span style="background-color: white; color: #373737; font-family: inherit; line-height: 24px;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/i&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="background-color: white; color: #373737; font-family: inherit; line-height: 24px;"&gt;So, for the record, that is just not true. Here's an implementation for the filterMap method:&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="background-color: white; color: #373737; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 15px; line-height: 24px;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;&lt;pre class="brush: scala"&gt;import scala.collection._&lt;br /&gt;import generic.CanBuildFrom&lt;br /&gt;import mutable.Builder&lt;br /&gt; &lt;br /&gt;class FilterMap[A, C &amp;lt;: Seq[A]](xs: C with SeqLike[A, C]) {&lt;br /&gt;     def filterMap[B, That](f: A =&amp;gt; Option[B])&lt;br /&gt;                     (implicit cbf: CanBuildFrom[C, B, That]): That = {&lt;br /&gt;       val builder: Builder[B, That] = cbf()&lt;br /&gt;       xs foreach { x =&amp;gt; val y = f(x); if (y.nonEmpty) builder += y.get }&lt;br /&gt;       builder.result()&lt;br /&gt;     }&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt;implicit def toFilterMap[A, C &amp;lt;: Seq[A]](xs: C with SeqLike[A, C]): FilterMap[A, C] = new FilterMap[A, C](xs)&lt;br /&gt;&lt;/pre&gt;&lt;span style="color: #373737; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;"&gt;&lt;span style="font-size: 15px; line-height: 24px;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="background-color: white; color: #373737; font-family: inherit; line-height: 24px;"&gt;Is this what the author wanted? No. He wanted too add a method that behaved like a normal collection method &lt;b style="font-style: italic;"&gt;to something that isn't a collection.&lt;/b&gt;&amp;nbsp;This is so crazy that, not surprisingly, people are misunderstanding him.&lt;/span&gt;&lt;br /&gt;&lt;span style="color: #373737; font-family: inherit;"&gt;&lt;span style="line-height: 24px;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: #373737; font-family: inherit;"&gt;&lt;span style="line-height: 24px;"&gt;Now, one may come up and say that Scala does do that (add methods to stuff that are not collection), with String and Array. Yes, it does, and it does so &lt;i&gt;by creating a completely new class with all these methods for each of them&lt;/i&gt;. Rest assured that if I create a completely new class for each one, I can add filterMap to String and Array too.&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: #373737; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;"&gt;&lt;span style="font-size: 15px; line-height: 24px;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-2495407794211942342?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/2495407794211942342/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2012/01/adding-methods-to-scala.html#comment-form' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/2495407794211942342'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/2495407794211942342'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2012/01/adding-methods-to-scala.html' title='Adding methods to Scala Collections'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-2311978234863327748</id><published>2011-12-27T16:27:00.005-02:00</published><updated>2012-01-23T18:21:14.498-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='beginner'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Using Scala API Documentation</title><content type='html'>One link that was missing from my post about &lt;a href="http://dcsobral.blogspot.com/2011/12/scala-on-web.html" target="_blank"&gt;Scala on the Web&lt;/a&gt; was the link to the Scala API documentation, often called "scaladoc" for short, after the tool that generates it. I tried to put it in, but it kind of broke the narrative and, to be honest, I have a lot to talk about the subject. So I decided to do a whole blog just about it.&lt;br /&gt;&lt;br /&gt;First of all, there are &lt;i&gt;two main links&lt;/i&gt;&amp;nbsp;that you can use to access it:&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;&lt;a href="http://www.scala-lang.org/api/current/index.html" target="_blank"&gt;The link to the API of the latest Scala release&lt;/a&gt;, and&lt;/li&gt;&lt;li&gt;&lt;a href="http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library/index.html" target="_blank"&gt;The link to the nightly Scala build of the next Scala version&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;Most of the time, I prefer the second link: it contains improvements to the Scaladoc tool, and the documentation often contains improvements. On the other hand, being a nightly release, it is subject to regresssions in the Scaladoc tool, and the documentation contains information that is not correct for the latest release. For that reason, I keep both links in my bookmarks.&lt;br /&gt;&lt;br /&gt;So, what else is there to say? Well, if you are new to Scala, a lot. Those familiar with the Java equivalent probably find it both familiar and strange: the screen is divided into left and right sections, the right section having description of classes and packages, while the left contains a list of them. Whereas Java splits package and class lists, however, Scala does not. And, of course, the look is completely different. These, however, are skin-deep differences, and I want to get to the bones of the matter.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="font-size: large;"&gt;&lt;b&gt;One Doc, Two Frames&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-vHpdsnaUc2A/Tvnyfw_LuXI/AAAAAAAAAfo/5iknrJnJfQ4/s1600/Selection_001.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="267" src="http://2.bp.blogspot.com/-vHpdsnaUc2A/Tvnyfw_LuXI/AAAAAAAAAfo/5iknrJnJfQ4/s640/Selection_001.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;The first thing I want you to notice are the two search boxes: one on the left, at the very top of the page, and one on the right, a bit lower. &lt;i&gt;Scaladoc is search-oriented!&lt;/i&gt;&amp;nbsp;That means you usually don't browse it, looking for stuff, but just type what you want. You can still browse, of course, which is useful when you don't know what you are looking for.&lt;br /&gt;&lt;br /&gt;On the left side you have the package hierarchy and classes, traits and objects belonging to the&amp;nbsp;packages. Note that classes, traits and objects can be members of &lt;i&gt;other&lt;/i&gt;&amp;nbsp;classes traits and objects, in which case they won't appear on the left.&lt;br /&gt;&lt;br /&gt;The right side contains information about a selected package, trait, class or object. The URL will change to match what is being displayed on the right side of the screen, so that you can easily bookmark or share links to specific class or object. At the present, there's no way to further refer to a member of a class, such as a specific method. This improvement will be added at some point in the future.&lt;br /&gt;&lt;br /&gt;Typically, you'll search or browse for a class on the left side of the screen, and then browse its contents on the left, or further search for a particular member of that class.&lt;br /&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="font-size: large;"&gt;&lt;b&gt;The Left Frame&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Let's drill down the left side, then, to get a better understanding of what's there and how to use it. At the top of the left frame, you'll see this:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-NXmC3xLejA8/Tvn40QqcAnI/AAAAAAAAAf0/oeQJuuDCFmg/s1600/Selection_009.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="72" src="http://4.bp.blogspot.com/-NXmC3xLejA8/Tvn40QqcAnI/AAAAAAAAAf0/oeQJuuDCFmg/s320/Selection_009.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Topmost is the search box, with a little "x" icon on the right hand to clear the search. Searching for something will &lt;i&gt;hide&lt;/i&gt;&amp;nbsp;any traits, objects and classes that don't match, as well as any packages that don't have any matching members.&lt;br /&gt;&lt;br /&gt;Right below that is &lt;i&gt;an index of all existing methods&lt;/i&gt;. Click on a letter and you'll get all methods starting with that letter, and the places they are defined at. Click on the hash symbol (#), and you'll get a page with all methods starting with a symbol instead of a letter. For example:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-dV4bg0irZ4U/Tvn6dV0A2xI/AAAAAAAAAgA/GAfLGRRoyi8/s1600/Selection_011.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="320" src="http://4.bp.blogspot.com/-dV4bg0irZ4U/Tvn6dV0A2xI/AAAAAAAAAgA/GAfLGRRoyi8/s320/Selection_011.png" width="315" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Finally, you have a small caption saying "&lt;b&gt;display packages only&lt;/b&gt;". Surprisingly, that's a clickable option. In fact, ScalaDoc is full of clickable parts, so if you are getting familiar with it, my advice is to try to click stuff, just to see what happens. Back to that caption, though, it switches the package hierarchy from displaying all entities to displaying packages only. Clicking it will give you something like this:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-O6bxuIVdy_o/Tvn7W_BS1II/AAAAAAAAAgM/Vh_OW70mQbQ/s1600/Selection_007.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="294" src="http://4.bp.blogspot.com/-O6bxuIVdy_o/Tvn7W_BS1II/AAAAAAAAAgM/Vh_OW70mQbQ/s320/Selection_007.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;If you click on "&lt;b&gt;show&lt;/b&gt;" on one of these packages, it will open up that particular package. If you click on "&lt;b&gt;display all entities&lt;/b&gt;", it will revert to the initial mode of display.&lt;br /&gt;&lt;br /&gt;Speaking of "&lt;b&gt;show&lt;/b&gt;", let's now look at the various parts of the entities list:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-yCIC7NwlI0E/Tvn7-S-IjLI/AAAAAAAAAgY/feESeZ-Jdn0/s1600/Selection_010.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="76" src="http://3.bp.blogspot.com/-yCIC7NwlI0E/Tvn7-S-IjLI/AAAAAAAAAgY/feESeZ-Jdn0/s320/Selection_010.png" width="320" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;The darker background indicates package or package objects, and the entities on the lighter background right below it are the classes, objects and traits belonging to that package, as indicated by the icons on their left. Note that, though package objects have other members such as methods, they do not appear on the left frame of Scaladoc.&lt;br /&gt;&lt;br /&gt;The icons for &lt;b&gt;"o&lt;/b&gt;", "&lt;b&gt;c&lt;/b&gt;" and "&lt;b&gt;t&lt;/b&gt;", in dark blue, green and light blue respectively, indicate objects, classes and traits. A name can be shared between an object and a trait or class, as seen for &lt;b&gt;Regex&lt;/b&gt;&amp;nbsp;above. Traits and classes cannot share the same name, however, so each name will have at most two icons beside it.&lt;br /&gt;&lt;br /&gt;&lt;i&gt;If you are not familiar with Scala, an object is a singleton, containing what, in Java, would be represented as static.&lt;/i&gt;&lt;br /&gt;&lt;br /&gt;One thing to realize here is that &lt;i&gt;everything in that image is clickable&lt;/i&gt;, except whitespace. You can click on "&lt;b&gt;scala.util.matching&lt;/b&gt;" and "&lt;b&gt;scala.util.parsing.combinator&lt;/b&gt;", on "&lt;b&gt;hide&lt;/b&gt;" and "&lt;b&gt;focus&lt;/b&gt;", on &lt;b&gt;"Regex&lt;/b&gt;" and "&lt;b&gt;RegexParsers&lt;/b&gt;", and on the icons.&lt;br /&gt;&lt;br /&gt;Clicking on a package name will show its traits, classes and objects on the right frame, unless the package is a &lt;i&gt;package object&lt;/i&gt;, in which case the right frame will show the other members it might have. This is important because many package objects contain implicit definitions used as helpers with that package. Check, for instance, &lt;a href="http://www.scala-lang.org/api/current/index.html#scala.sys.process.package" target="_blank"&gt;scala.sys.process&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Clicking on "&lt;b&gt;hide&lt;/b&gt;" will hide the entities belonging to that particular package, but not any subpackage that might exist. The text will then change to "&lt;b&gt;show&lt;/b&gt;", which will revert this action upon being clicked.&lt;br /&gt;&lt;br /&gt;Clicking on "&lt;b&gt;focus&lt;/b&gt;" will hide all other packages from view, like this:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-2RKUaQriDAA/TvoAtmx8s-I/AAAAAAAAAgk/fiYFaVS-9LU/s1600/Selection_012.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" src="http://2.bp.blogspot.com/-2RKUaQriDAA/TvoAtmx8s-I/AAAAAAAAAgk/fiYFaVS-9LU/s1600/Selection_012.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Clicking on the "&lt;b&gt;x&lt;/b&gt;" icon that appears will revert this action.&lt;br /&gt;&lt;br /&gt;Clicking on an icon for object, class or trait will show information for it on the right frame, as will clicking on the text itself. If an object shares a name with a trait or class, however, clicking on the text will show &lt;i&gt;not the object&lt;/i&gt;, but the class or trait, following the assumption that this is what people want most of the time.&lt;br /&gt;&lt;br /&gt;On recent ScalaDoc versions, clicking on an entity will also move the focus to the search box on the right frame, so that you can instantly type&lt;br /&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="font-size: large;"&gt;&lt;b&gt;The Right Frame&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;To begin the discussion of the right, I picked &lt;a href="http://www.scala-lang.org/api/current/index.html#scala.collection.GenSeq" style="font-weight: bold;" target="_blank"&gt;GenSeq&lt;/a&gt;, which is rich enough in ScalaDoc UI components, but (relatively) poor enough in actual content to fit in here.&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-l5flMnAJfrc/TvoE8n0czQI/AAAAAAAAAgw/7nbIVK7s99g/s1600/Selection_013.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="406" src="http://2.bp.blogspot.com/-l5flMnAJfrc/TvoE8n0czQI/AAAAAAAAAgw/7nbIVK7s99g/s640/Selection_013.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;You may have wondered why the search box is not at the top on the right frame, like it is on the left. The reason for it is our starting point in explaining the right frame.&lt;br /&gt;&lt;br /&gt;&lt;i&gt;The right frame is divided in three parts&lt;/i&gt;, the topmost two being shown above. The first part contains general information about the selected entity, and it comprises everything from the top until right before the search box.&amp;nbsp;The second part starts with the search box, and is comprised of everything in that gray background. This part contains &lt;b style="font-style: italic;"&gt;display options&lt;/b&gt;&amp;nbsp;that affect the third part of the right frame.&amp;nbsp;The third part contains all members of the selected entity, with individual information for each one.&lt;br /&gt;&lt;br /&gt;From the top, then, we have a green or blue background (the former for traits and classes, the latter for objects, packages and package objects) on which the name of the entity is prominently displayed. A big icon beside it indicates what kind of entity it is: &lt;b&gt;t&lt;/b&gt; for traits, &lt;b&gt;c&lt;/b&gt; for classes, &lt;b&gt;o&lt;/b&gt; for objects and &lt;b&gt;p&lt;/b&gt; for packages and package objects alike.&lt;br /&gt;&lt;br /&gt;If the icon is slightly folded on the bottom, like the one in the example, clicking on it (or the entity name) will switch the right frame to the &lt;i&gt;companion&lt;/i&gt; of that entity. If you are not familiar with Scala, objects, traits and classes that share a name are said to be companions to each other. Clicking on the&amp;nbsp;&lt;b&gt;GenSeq&lt;/b&gt;&amp;nbsp;trait above, then, will display the &lt;b&gt;GenSeq&lt;/b&gt;&amp;nbsp;object.&lt;br /&gt;&lt;br /&gt;In a smaller font above the entity name is the full path to that entity. Clicking on a path component will display that component.&lt;br /&gt;&lt;br /&gt;After that, in a gray background, comes a description of all classes, traits and type parameters used in the definition of that entity. It does not list classes or traits that are inherited -- that is available further below. Not to sound too repetitive, but clicking on any of the classes and traits will display it... Also, moving the mouse over one of these names will show the full path for that name.&lt;br /&gt;&lt;br /&gt;What follows is the full description and attributes associated with that entity. I deliberately choose one extremely poor in those, so that I could concentrate on what ScalaDoc provides. One of those things is the link to the source code in which that entity is defined. Not all Scala projects provide that attribute, but Scala API itself does. The link currently points to the web interface to the old Subversion repository -- I presume this will be switched to the new repository on Github in the near future. At any rate, all niceties of source version control systems are available on that link. For the Scala API, anyway.&lt;br /&gt;&lt;br /&gt;"&lt;b&gt;Linear Supertypes&lt;/b&gt;" and "&lt;b&gt;Known Subclasses&lt;/b&gt;" at the bottom of this part can be expanded upon click, to display the exact linearization of an entity's supertypes -- the inheritance precedence -- and all known subclasses. For example, for &lt;b&gt;&lt;a href="http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.List" target="_blank"&gt;List&lt;/a&gt;&lt;/b&gt;&amp;nbsp;it will show this:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://4.bp.blogspot.com/-Q4bMc_hWXCU/TvoPqvb8ozI/AAAAAAAAAhg/uFUPf-x-FTo/s1600/Selection_017.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="108" src="http://4.bp.blogspot.com/-Q4bMc_hWXCU/TvoPqvb8ozI/AAAAAAAAAhg/uFUPf-x-FTo/s640/Selection_017.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Also shown above is the tool tip indicating the full path of one of the supertypes being pointed at, just like mentioned above for entity declaration.&lt;br /&gt;&lt;br /&gt;Let's now look at the second part of the right frame:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-_kW-ylAc5NQ/TvoQ6VL7DjI/AAAAAAAAAhs/kgX8S3INJiw/s1600/Selection_013b.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="168" src="http://2.bp.blogspot.com/-_kW-ylAc5NQ/TvoQ6VL7DjI/AAAAAAAAAhs/kgX8S3INJiw/s640/Selection_013b.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;The search box works pretty much like the one on the left frame, hiding anything that isn't a match, but it includes descriptions on the search as well. Search for a verb, therefore, will often yield good results, unless the verb is too general.&lt;br /&gt;&lt;br /&gt;One particularly nice feature, available on recent versions, is that typing multiple words will search for matches of any one of the words, which makes it easy to display two methods close together on the screen.&lt;br /&gt;&lt;br /&gt;All other options below the search box also change the way things are shown in the third part. The default &lt;b&gt;Ordering&lt;/b&gt; mode, &lt;b&gt;Alphabetic&lt;/b&gt;, will display &lt;i&gt;all non-private members of an entity&lt;/i&gt;, separated in categories which we'll shown below, in alphabetical order. This is different than Java, which only shows full information for members defined or overridden on that class/interface.&lt;br /&gt;&lt;br /&gt;Clicking &lt;b&gt;"By inheritance&lt;/b&gt;" will change the display mode to separate the members according to where it was last defined/overridden. Full information will still be displayed, and the members will still be shown in alphabetical order in their own section.&lt;br /&gt;&lt;br /&gt;The &lt;b&gt;Inherited&lt;/b&gt;&amp;nbsp;options let you easily filter out inherited methods. Clicking on "&lt;b&gt;Hide All&lt;/b&gt;" will toggle off all supertypes, leaving only the entity itself selected. This will hide methods that are not abstract, defined or overridden on the entity. For &lt;b&gt;GenSeq&lt;/b&gt;, for example only two methods will be displayed: &lt;b&gt;seq&lt;/b&gt;&amp;nbsp;and &lt;b&gt;companion&lt;/b&gt;.&lt;br /&gt;&lt;br /&gt;Note that clicking on "&lt;b&gt;Show all&lt;/b&gt;" &lt;i&gt;will not&lt;/i&gt;&amp;nbsp;select &lt;b&gt;AnyVal&lt;/b&gt;,&amp;nbsp;&lt;b&gt;AnyRef&lt;/b&gt;&amp;nbsp;or &lt;b&gt;Any&lt;/b&gt;. Because the methods defined on these are available on pretty much everything, one rarely needs to see these methods.&lt;br /&gt;&lt;br /&gt;Because many times you might be interested in a particular aspect of an entity, you can also toggle each supertype individually. You can do so to display the methods on &lt;b&gt;Any&lt;/b&gt;, for example, or you could look into what &lt;b&gt;Function1&lt;/b&gt;&amp;nbsp;has to offer to &lt;b&gt;List&lt;/b&gt;.&lt;br /&gt;&lt;br /&gt;The last option, &lt;b&gt;Visibility&lt;/b&gt;, will toggle between displaying only public members and everything except private members.&lt;br /&gt;&lt;br /&gt;The last part of the right frame, as mentioned, contains all members of that entity. These are divided into &lt;i&gt;type members&lt;/i&gt;&amp;nbsp;and &lt;i&gt;value members&lt;/i&gt;. A type member is a &lt;i&gt;trait&lt;/i&gt;, a &lt;i&gt;class&lt;/i&gt;&amp;nbsp;or a &lt;i&gt;type&lt;/i&gt;, and value members are everything else. For example, the &lt;a href="http://www.scala-lang.org/api/current/index.html#scala.util.matching.Regex$" target="_blank"&gt;object &lt;b&gt;Regex&lt;/b&gt;&lt;/a&gt;&amp;nbsp;contains this:&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-jukXxXs8nu8/TvoXLt4l07I/AAAAAAAAAh4/vNn1zsjLo2Q/s1600/Selection_018.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="270" src="http://2.bp.blogspot.com/-jukXxXs8nu8/TvoXLt4l07I/AAAAAAAAAh4/vNn1zsjLo2Q/s640/Selection_018.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Note that anything that shows up as a &lt;i&gt;type member&lt;/i&gt;&amp;nbsp;of anything but a package will not be displayed on the left frame, even though you can display it on the right frame by clicking on a link to it.&lt;br /&gt;&lt;br /&gt;Value members are actually divided in three separate sections: abstract value members, concrete value members and deprecated value members. These are shown in that precise order, so that one can easily see all members that must be implemented to make a concrete class, and don't get the screen polluted by methods they shouldn't be using -- deprecated methods -- when browsing.&lt;br /&gt;&lt;br /&gt;Let's look at some important points of value member definitions. The snapshot below was taken from a &lt;b&gt;List&lt;/b&gt;&amp;nbsp;with members filtered by "map":&lt;br /&gt;&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-ecJPeOdnb4o/TvoY7MXwBOI/AAAAAAAAAiE/FWMexIdpZ48/s1600/Selection_019.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="400" src="http://3.bp.blogspot.com/-ecJPeOdnb4o/TvoY7MXwBOI/AAAAAAAAAiE/FWMexIdpZ48/s640/Selection_019.png" width="640" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;By default, only a member's definition and the first sentence of its description are shown, like method &lt;b&gt;groupBy&lt;/b&gt;&amp;nbsp;above. Clicking on either the small arrow on the left or on the definition itself will show the full information for that member, as seen in the two definitions for &lt;b&gt;map&lt;/b&gt;.&lt;br /&gt;&lt;br /&gt;Since Scala supports method overload, methods can have multiple definitions. In this particular case, however, the first definition is not a real one -- &lt;i&gt;this is indicated by the &lt;b&gt;[use case]&lt;/b&gt;&amp;nbsp;tag&lt;/i&gt;. It is important to understand what use cases are, for two reasons: first, they represent the most common way to use the method, and, second, they are lies. Well-meaning lies, but lies.&lt;br /&gt;&lt;br /&gt;Compare the definition of the two &lt;b&gt;map&lt;/b&gt;&amp;nbsp;methods shown. Clearly, the second definition has a lot going on, whereas the first definition is pretty clear: on a &lt;b&gt;List[A]&lt;/b&gt;&amp;nbsp;(see definition for &lt;b&gt;List&lt;/b&gt;), the &lt;b&gt;map&lt;/b&gt;&amp;nbsp;method takes a function that converts an &lt;b&gt;A&lt;/b&gt;&amp;nbsp;into a &lt;b&gt;B&lt;/b&gt;, and returns a &lt;b&gt;List[B]&lt;/b&gt;.&lt;br /&gt;&lt;br /&gt;Though that definition works very fine for &lt;b&gt;List&lt;/b&gt;, the &lt;b&gt;map&lt;/b&gt;&amp;nbsp;method is not defined on &lt;b&gt;List&lt;/b&gt;, but much &amp;nbsp;higher on the hierarchy. And what works for &lt;b&gt;List&lt;/b&gt;&amp;nbsp;won't work for a &lt;b&gt;BitSet&lt;/b&gt;, for example: since a &lt;b&gt;BitSet&lt;/b&gt;&amp;nbsp;is a &lt;b&gt;Set[Int]&lt;/b&gt;, if you map those&lt;b&gt;&amp;nbsp;Int&lt;/b&gt;&amp;nbsp;into &lt;b&gt;String&lt;/b&gt;, you won't be able to return a &lt;b&gt;BitSet&lt;/b&gt;! After all, a &lt;b&gt;BitSet&lt;/b&gt;&amp;nbsp; cannot be a &lt;b&gt;Set[String]&lt;/b&gt;. The same thing happens in other cases: a &lt;b&gt;WrappedString&lt;/b&gt;&amp;nbsp;is a &lt;b&gt;Seq[Char]&lt;/b&gt;, a &lt;b&gt;Map[A, B]&lt;/b&gt;&amp;nbsp;is a &lt;b&gt;Iterable[Tuple2[A, B]]&lt;/b&gt;&amp;nbsp;(aka &lt;b&gt;Iterable[(A, B)]&lt;/b&gt;), etc. In any of these cases, a &lt;b&gt;map&lt;/b&gt;&amp;nbsp;definition like in the use case won't work.&lt;br /&gt;&lt;br /&gt;So the actual definition of &lt;b&gt;map&lt;/b&gt;&amp;nbsp;is the second one, which can handle all of these cases. If you need precise information about &lt;b&gt;map&lt;/b&gt;&amp;nbsp;-- for example, if you are extended Scala collections -- you can look it up. On the other hand, if you just want to know how a method is used, the use case should be much easier to understand.&lt;br /&gt;&lt;br /&gt;Most of the remaining information is pretty obvious: a description follows, and then various attributes describing how parameters are supposed to be used, what the return type is, etc.&lt;br /&gt;&lt;br /&gt;The final interesting thing here is the &lt;b&gt;Definition Classes&lt;/b&gt;&amp;nbsp;shown below each method. This only appears when a method has been inherited from elsewhere, and it indicates both where it was originally declared (which might have been as&amp;nbsp;&lt;i&gt;abstract&lt;/i&gt;), and all places where it was &lt;i&gt;overridden&lt;/i&gt;, &lt;i&gt;ie&lt;/i&gt;, the implementation has been changed.&lt;br /&gt;&lt;br /&gt;And this concludes the tutorial on using the Scala API documentation, as well as the docs for any other library written in Scala. Looking back, it is much longer (and took much more time to write) than I first thought. Yet, rest assured that using ScalaDoc becomes second nature very fast!&lt;br /&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-2311978234863327748?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/2311978234863327748/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2011/12/using-scala-api-documentation.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/2311978234863327748'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/2311978234863327748'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2011/12/using-scala-api-documentation.html' title='Using Scala API Documentation'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/-vHpdsnaUc2A/Tvnyfw_LuXI/AAAAAAAAAfo/5iknrJnJfQ4/s72-c/Selection_001.png' height='72' width='72'/><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-9074704236558620049</id><published>2011-12-23T16:26:00.001-02:00</published><updated>2011-12-23T16:26:12.720-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='beginner'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Scala on the Web</title><content type='html'>I was wondering how to approach Scala on a dojo about it, and I kept returning to the idea that I should first introduce Scala on the Web. So, how would I go about it? What sites would I mention? Scala has grown such a rich ecosystem around it since I first started using it that I'm actually feeling a bit lost nowadays. And, let me tell you, that's a nice change! :-)&lt;br /&gt;&lt;br /&gt;Nevertheless, the problem remains. As I started compiling the sites in my head, I quickly realized I'd have to write it down somewhere, and where better than in my own, dusty blog? So, here it is: the DCS guide to Scala on the Web!&lt;br /&gt;&lt;br /&gt;For a long time, the starting point and central hub to Scala resources has been the &lt;a href="http://www.scala-lang.org/" target="_blank"&gt;Scala-Lang site&lt;/a&gt;. From there you can download Scala, find documentation, guides, support information, news... and it has become dated. Mind you, it still is a great resource, but some alternatives -- some &lt;i&gt;official&lt;/i&gt;&amp;nbsp;alternatives! -- have emerged since then.&lt;br /&gt;&lt;br /&gt;One of them is &lt;a href="http://www.typesafe.com/" target="_blank"&gt;Typesafe&lt;/a&gt;. Typesafe is a startup created around supporting Scala and related technologies. While this might not sound like a starter resource, they provide the &lt;a href="http://www.typesafe.com/stack" target="_blank"&gt;Typesafe Stack&lt;/a&gt;, a set of tools including not only the language, but also Eclipse support, a build tool, a distributed system framework and a web framework. I think they plan to add more elements to it, but, anyway, go to their &lt;a href="http://www.typesafe.com/stack/download" target="_blank"&gt;DOWNLOAD&lt;/a&gt; link and you'll have Scala up-and-running in no time.&lt;br /&gt;&lt;br /&gt;Another important resource is the &lt;a href="http://docs.scala-lang.org/" target="_blank"&gt;Documentation Site&lt;/a&gt;. A newly designed site to replace the old one on scala-lang. Scala-lang even has a link to it, though it still keeps the old one as well. Here you'll find guides, tutorials, cheatsheets, FAQ, and even a glossary of Scala terms and a Scala Style Guide. Oh, and a link to the &lt;a href="http://wiki.scala-lang.org/" target="_blank"&gt;Scala Wiki&lt;/a&gt; as well.&lt;br /&gt;&lt;br /&gt;While on the wiki, please pay close attention to the &lt;a href="https://wiki.scala-lang.org/display/SW/Tools+and+Libraries" target="_blank"&gt;Tools and Libraries&lt;/a&gt;&amp;nbsp;page. You might not find everything there, and you might find things that have not been kept up-to-date, but even so it is an invaluable resource.&lt;br /&gt;&lt;br /&gt;And speaking of FAQs, some brave souls took the time to compile &lt;a href="http://stackoverflow.com/tags/scala/info" target="_blank"&gt;Stack Overflow Scala Tutorial&lt;/a&gt;! The thing is nothing short of amazing: dozens, maybe more than a hundred of the most important questions categorized in 31 different topics, from "Introduction to Scala" to "Functional Scala", with a side dish of five additional topics for further learning.&lt;br /&gt;&lt;br /&gt;By the way, if you don't know &lt;a href="http://stackoverflow.com/" target="_blank"&gt;Stack Overflow&lt;/a&gt;, it is a question&amp;amp;answer site about programming questions -- only it actually works and is enjoyable to use, as opposed to their competition. More importantly, the Scala community is well represented on Stack Overflow, and you can use it to get questions about Scala answered in no time. In fact, it has probably been asked and answered already. :-)&lt;br /&gt;&lt;br /&gt;The only problem with Stack Overflow is that it doesn't search for symbols, and Scala has a fair share of them. If you have a question about a symbol, use the &lt;a href="http://symbolhound.com/" target="_blank"&gt;Symbol Hound&lt;/a&gt;&amp;nbsp;site to search for it.&lt;br /&gt;&lt;br /&gt;What else? Well, there's &lt;a href="http://www.planetscala.com/" target="_blank"&gt;Planet Scala&lt;/a&gt;, a blog feed aggregator, and &lt;a href="http://implicit.ly/" target="_blank"&gt;Implicit.ly&lt;/a&gt;, a feed of Scala projects that is automatically fed by a plugin on the build system. It doesn't contain all Scala projects, of course, but it goes a long way.&lt;br /&gt;&lt;br /&gt;And if you want to try Scala without ever installing it, there's &lt;a href="http://www.simplyscala.com/" target="_blank"&gt;Simply Scala&lt;/a&gt;, a Scala tutorial that let you execute the sample code, as well as try out code of your own.&lt;br /&gt;&lt;br /&gt;If you want to get more dee involved with Scala itself, look at its&amp;nbsp;&lt;a href="https://github.com/scala" target="_blank"&gt;github account&lt;/a&gt;. &lt;a href="https://github.com/scala/scala" target="_blank"&gt;Scala,&lt;/a&gt;&amp;nbsp;compiler and library,&amp;nbsp;is there, as well as &lt;a href="https://github.com/scala/scala.github.com" target="_blank"&gt;the documentation site&lt;/a&gt;&amp;nbsp;I mentioned earlier.&lt;br /&gt;&lt;br /&gt;Ok, I'm sure I left a bunch of sites out (like some news aggregators -- I don't follow them, but if you do, send me the link and I'll put them up), but let's address now some of the basic tools most people will be searching for.&lt;br /&gt;&lt;br /&gt;I spoke earlier about a build tool, so let's discuss it a bit. The build tool of preference for Scala is &lt;a href="https://github.com/harrah/xsbt/wiki" target="_blank"&gt;SBT&lt;/a&gt;. If you search for it on the Internet, you might come up on the link to the old version (up to 0.7.7), which is hosted on Google Code. The newer versions (0.10.0+) are hosted on Github, and are incompatible with the older ones. Make sure you get the new version.&lt;br /&gt;&lt;br /&gt;Alternatively, you may opt to install the &lt;a href="https://github.com/paulp/sbt-extras" target="_blank"&gt;SBT Extras&lt;/a&gt; script instead. It's the same SBT, but with a starter script that provides a richer set of options. There's also a couple of &lt;a href="https://github.com/harrah/xsbt/wiki/Scripts" target="_blank"&gt;alternate starter scripts&lt;/a&gt;&amp;nbsp;on the SBT site, called "screpl" and "scalas", which uses SBT to load dependencies while starting Scala's REPL (that's an "interpreter" console, so to speak) or starting Scala shell scripts.&lt;br /&gt;&lt;br /&gt;You don't actually need to download Scala at all if you install SBT: SBT will download whatever version of Scala you tell it your project uses, requiring only that you have a JVM installed.&lt;br /&gt;&lt;br /&gt;What about testing, what should you use? Scala is in the unfortunate position of having two excellent testing frameworks: &lt;a href="http://www.scalatest.org/" target="_blank"&gt;ScalaTest&lt;/a&gt; and &lt;a href="http://specs2.org/" target="_blank"&gt;Specs2&lt;/a&gt;. They are both mature, fully-featured, actively developed and supported, and with big communities. There's no way to recommend one over the other: it really comes down to personal preference.&lt;br /&gt;&lt;br /&gt;Both of them also support &lt;a href="http://code.google.com/p/scalacheck/" target="_blank"&gt;ScalaCheck&lt;/a&gt;, a testing framework that test stuff by automatically generating input and verifying if the specified conditions hold true. ScalaCheck is great to find boundary conditions, and, as mentioned, you can use its checker under both ScalaTest and Specs2.&lt;br /&gt;&lt;br /&gt;You can use existing Java mocking frameworks (Specs2 has special support for Mockito, though Specs, the older version, supported JMock and EasyMock as well), but there's a Scala mocking framework available as well: &lt;a href="http://scalamock.org/" target="_blank"&gt;ScalaMock&lt;/a&gt;. ScalaMock has advanced features, such as mocking Scala objects (equivalent to Java static members) and even constructors! That means you can actually mock the behavior of a "new" statement without replacing it with factories or dependency injection.&lt;br /&gt;&lt;br /&gt;To wrap it up, web frameworks and database access.&lt;br /&gt;&lt;br /&gt;Scala has many &lt;a href="https://wiki.scala-lang.org/display/SW/Tools+and+Libraries#ToolsandLibraries-Frameworks" target="_blank"&gt;web frameworks&lt;/a&gt; available, and there's even a healthy reuse of components between these frameworks. For instance, &lt;a href="https://github.com/scalate/scalate" target="_blank"&gt;Scalate&lt;/a&gt;, a templating engine that can even serve as web server on a stretch, seems to be used by pretty much everyone nowadays. But let's look into the main alternatives.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://liftweb.net/" target="_blank"&gt;Lift&lt;/a&gt; is the oldest one (at least among the more serious frameworks), and has a strong community. David Pollack, It's author looked into a number of successful frameworks and decided to pick the best of the best, add a few twists of his own, and use Scala's power to provide an incredible piece of software. Among Lift's strengths, there's a strong separation of concerns (web page design and code are strictly separated), a seamless AJAX/Comet integration, powerful wizards for common concerns, and a design that took security considerations into account right from the beginning. If you do go with Lift, however, please make use of their mailing list as support -- that is their main support channel, and they prefer to concentrate their help there.&lt;br /&gt;&lt;br /&gt;To those who are familiar with Sinatra, there's &lt;a href="https://github.com/scalatra/scalatra#readme" target="_blank"&gt;Scalatra&lt;/a&gt;&amp;nbsp;and &lt;a href="http://bowlerframework.org/" target="_blank"&gt;Bowler&lt;/a&gt;, that latter being built on top of the former.&amp;nbsp;And I might well be mistaken, but &lt;a href="http://circumflex.ru/index.html" target="_blank"&gt;Circumflex&lt;/a&gt;&amp;nbsp;seems to go the same way as well.&lt;br /&gt;&lt;br /&gt;If providing a web service is just a small part of your application, you might want to opt for &lt;a href="http://unfiltered.databinder.net/" target="_blank"&gt;Unfiltered&lt;/a&gt; instead. With Unfiltered, the web server is a library in your application, instead of your application being a servlet inside a framework.&lt;br /&gt;&lt;br /&gt;And if what you really need are web services to interconnect systems, try &lt;a href="https://github.com/jdegoes/blueeyes" target="_blank"&gt;Blue Eyes&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Now, there are a lot of other web frameworks, I'll mention just one other. Typesafe has decided to integrate the &lt;a href="http://scala.playframework.org/" target="_blank"&gt;Play! Framework&lt;/a&gt;&amp;nbsp;into its stack. Play! offers the ease of web development that PHP has, but with all the advantages Scala has to offer.&lt;br /&gt;&lt;br /&gt;Which leaves us, at last, with databases. Again, there are &lt;a href="https://wiki.scala-lang.org/display/SW/Tools+and+Libraries#ToolsandLibraries-DataStorage" target="_blank"&gt;many option&lt;/a&gt;s to choose from. If you are doing web development, the framework of your choice probably already has some recommended libraries to deal with it -- their own or others (did I mention that there's a healthy reuse of components? :). I suggest you go with that.&lt;br /&gt;&lt;br /&gt;If not, I can make some suggestions. I don't have personal experience with this, so I'm mostly recommending based on what I perceive to be preferred choices with active communities. There's &lt;a href="http://scalaquery.org/" target="_blank"&gt;ScalaQuery&lt;/a&gt;, which has always been a favorite of mine (just waiting for a project where I can put it to use :). &lt;a href="https://github.com/nkallen/querulous" target="_blank"&gt;Querulous&lt;/a&gt; and &lt;a href="http://squeryl.org/" target="_blank"&gt;Squeryl&lt;/a&gt;&amp;nbsp;also get a lot of traffic, but once you get to NoSQL, the main choice seems to be MongoDB's &lt;a href="https://github.com/mongodb/casbah" target="_blank"&gt;Casbah&lt;/a&gt;&amp;nbsp;driver. I have played a little bit with it, and it is certainly quite easy to get up and running for small projects or experiments.&lt;br /&gt;&lt;br /&gt;Do look into the existing choices, however, as there might be something better suited to your needs.&lt;br /&gt;&lt;br /&gt;And if you haven't payed attention the first time I linked to it, the &lt;a href="https://wiki.scala-lang.org/display/SW/Tools+and+Libraries" target="_blank"&gt;Wiki of Tools and Libraries&lt;/a&gt; is a very good resource to get started on specialized, well, tools and libraries. :-)&lt;br /&gt;&lt;br /&gt;If you are new to Scala, I hope this can get you going. If you are experienced, I hope you can use this when helping others. Of course, this post will get old, the links will get outdated, and new cool stuff will come up.&lt;br /&gt;&lt;br /&gt;For now, enjoy!&lt;br /&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-9074704236558620049?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/9074704236558620049/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2011/12/scala-on-web.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/9074704236558620049'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/9074704236558620049'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2011/12/scala-on-web.html' title='Scala on the Web'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-1908273181608052454</id><published>2011-10-12T15:13:00.000-03:00</published><updated>2011-10-14T00:37:28.158-03:00</updated><title type='text'>String Interpolation on 2.10?</title><content type='html'>Happiness is made of small things...&lt;br /&gt;&lt;br/&gt;&lt;pre class="brush:scala"&gt;Welcome to Scala version 2.10.0.r25815-b20111010230908 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_23).&lt;br /&gt;Type in expressions to have them evaluated.&lt;br /&gt;Type :help for more information.&lt;br /&gt;&lt;br /&gt;scala&amp;gt; val x = 1&lt;br /&gt;x: Int = 1&lt;br /&gt;&lt;br /&gt;scala&amp;gt; "\{x}"&lt;br /&gt;res0: String = 1&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Requires the -Xexperimental flag. This test case reveals even more interesting things:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;scala&amp;gt; val x = 1.1&lt;br /&gt;x: Double = 1.1&lt;br /&gt;&lt;br /&gt;scala&amp;gt; println("We have a \{ x ;2.2f}% chance of success")&lt;br /&gt;We have a 1,10% chance of success&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Mind you, there's a lot of things that have been hidden behind -Xexperimental, some of them for a long time now, and some of them ended up canned.&lt;br /&gt;&lt;b&gt;Edit:&lt;/b&gt; The proposal for this extension can be found &lt;a href="http://scala.github.com/sips//pending/string-interpolation.html"&gt;here&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-1908273181608052454?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/1908273181608052454/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2011/10/string-interpolation-on-210.html#comment-form' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/1908273181608052454'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/1908273181608052454'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2011/10/string-interpolation-on-210.html' title='String Interpolation on 2.10?'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-4201387473043757024</id><published>2011-08-30T10:26:00.001-03:00</published><updated>2011-08-30T10:42:37.196-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='linux ubuntu boot grub'/><title type='text'>A quick detour through Grub and choosing default operating system</title><content type='html'>I'm going to do a quick detour to talk about &lt;a href="http://www.gnu.org/software/grub/"&gt;grub&lt;/a&gt;.&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Grub is the boot manager of choice for Linux systems, and the one installed by default by &lt;a href="http://www.ubuntu.com/"&gt;Ubuntu&lt;/a&gt;, among others. My desktop at home dual boots between Ubuntu and Windows (I have gaming needs, after all), and Windows is the default operating system, so my wife doesn't have to do anything.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Setting that default was not exactly trivial. The web abounds with instructions on how to choose the default, most of which refer to the previous version of grub. About the newer version, not so much information.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, in the end I used Ubuntu's &lt;a href="https://help.ubuntu.com/community/StartUpManager"&gt;Startup Manager&lt;/a&gt;&amp;nbsp;to set this up. By the way, can anyone explain to me why you use Startup Manager to choose which OS to boot, and &lt;a href="http://www.marzocca.net/linux/bum.html"&gt;Bootup Manager&lt;/a&gt;&amp;nbsp;to choose which processes will start? Sorry, I digress...&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;That worked nicely until the day I upgraded the system, at which point a new entry was created, changing the relative position of the Windows boot. That was disagreeable, so I decided to take a closer look.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The configuration used by grub during boot is located at &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;/boot/grub&lt;/span&gt;, in particular &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;/boot/grub/grub.cfg&lt;/span&gt;. But you shouldn't edit this file directly -- it is generated from the scripts located at &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;/etc/grub&lt;/span&gt;, plus configuration on &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;/etc/default/grub&lt;/span&gt;. Usually, it is this latter file you should edit.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;To change the default operating system, you edit &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;/etc/default/grub&lt;/span&gt;, change the setting&amp;nbsp;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;GRUB_DEFAULT&lt;/span&gt;, and then run &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;update-grub&lt;/span&gt;. Alas, the Startup Manager will do all this for you, but there is one thing the Startup Manager doesn't do...&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, here's the trick. The&amp;nbsp;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;GRUB_DEFAULT&lt;/span&gt;&amp;nbsp;is usually set to a number, indicating the relative position of the entry you want, but it can also be set to a name! To see what the entry names are, you can do a "&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;grep menuentry /boot/grub/grub.cfg&lt;/span&gt;" -- the names are the strings between single or double-quotes right after "&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;menuentry&lt;/span&gt;". For example:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;&lt;/span&gt;&lt;br /&gt;&lt;pre&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;$ grep menuentry /boot/grub/grub.cfg&lt;br /&gt;menuentry 'Ubuntu, with Linux 2.6.38-11-generic' --class ubuntu --class gnu-linux --class gnu --class os {&lt;br /&gt;menuentry 'Ubuntu, with Linux 2.6.38-11-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os {&lt;br /&gt;menuentry 'Ubuntu, with Linux 2.6.38-10-generic' --class ubuntu --class gnu-linux --class gnu --class os {&lt;br /&gt;menuentry 'Ubuntu, with Linux 2.6.38-10-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os {&lt;br /&gt;menuentry 'Ubuntu, with Linux 2.6.38-8-generic' --class ubuntu --class gnu-linux --class gnu --class os {&lt;br /&gt;menuentry 'Ubuntu, with Linux 2.6.38-8-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os {&lt;br /&gt;menuentry "Memory test (memtest86+)" {&lt;br /&gt;menuentry "Memory test (memtest86+, serial console 115200)" {&lt;br /&gt;&lt;/span&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This also shows why Startup Manager uses numbers instead of names: so that the latest Linux is always chosen. This seems a poor choice for me, for anything &lt;i&gt;except&lt;/i&gt;&amp;nbsp;the first entry, but there you go.&lt;br /&gt;&lt;br /&gt;Anyway, once you got the name, all you have to do is edit&amp;nbsp;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;/etc/default/grub&lt;/span&gt;, change the setting&amp;nbsp;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;GRUB_DEFAULT&lt;/span&gt;, so that it is set to the name of the entry you want (don't forget the quotes), and then run&amp;nbsp;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;update-grub&lt;/span&gt;.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-4201387473043757024?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/4201387473043757024/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2011/08/quick-detour-through-grub-and-choosing.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/4201387473043757024'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/4201387473043757024'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2011/08/quick-detour-through-grub-and-choosing.html' title='A quick detour through Grub and choosing default operating system'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-4389316983925772528</id><published>2011-07-05T13:55:00.000-03:00</published><updated>2011-07-05T13:55:20.750-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='algorithm'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Build a binary tree from pre-order traversal and in-order traversal</title><content type='html'>This post comes from &lt;a href="http://www.ihas1337code.com/2011/04/construct-binary-tree-from-inorder-and-preorder-postorder-traversal.html"&gt;i has 1337 code&lt;/a&gt; by way of &lt;a href="http://analgorithmaday.blogspot.com/2011/05/construct-binary-tree-from-pre-order.html"&gt;An Algorithm a Day&lt;/a&gt;. I'm really just posting this to show the power of Scala collections.&lt;br /&gt;&lt;br /&gt;The idea is that you have two sequential representations of a tree: one for in-order traversal, and the order for pre-order traversal. Just one of these representations are not enough to reconstruct the tree, but the two of them, in the absence of duplicate elements, is. See the links above for an example.&lt;br /&gt;&lt;br /&gt;The problem lends itself to recursive solutions, but there's some list manipulation required to build the input for the recursive steps. The key point of the algorithm is the realization that the first element of pre-order is the root, and every element to the left of said root in the in-order belongs to the left of the tree, and every element to the right belongs to the right of the tree. The rest is pretty trivial.&lt;br /&gt;&lt;br /&gt;Even so, Scala makes the trivial, well, trivial. Here's the full code:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;case class Tree[T](el: T, left: Option[Tree[T]], right: Option[Tree[T]])&lt;br /&gt;&lt;br /&gt;def mkTree[T](preorder: List[T], inorder: List[T]): Option[Tree[T]] = preorder.headOption map { head =&gt;&lt;br /&gt;    val (left, _ :: right) = inorder span (head !=)&lt;br /&gt;    Tree(head, &lt;br /&gt;         mkTree(preorder filter (left contains), left), &lt;br /&gt;         mkTree(preorder filter (right contains), right))&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Note: I'm using &lt;code&gt;List&lt;/code&gt; instead of &lt;code&gt;Seq&lt;/code&gt; so that I can use the &lt;code&gt;::&lt;/code&gt; extractor.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-4389316983925772528?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/4389316983925772528/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2011/07/build-binary-tree-from-pre-order.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/4389316983925772528'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/4389316983925772528'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2011/07/build-binary-tree-from-pre-order.html' title='Build a binary tree from pre-order traversal and in-order traversal'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>4</thr:total><georss:featurename>Distrito Federal, Brasil</georss:featurename><georss:point>-15.826691 -47.9218204</georss:point><georss:box>-16.102796 -48.4111789 -15.550586000000001 -47.4324619</georss:box></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-358664946218534453</id><published>2011-06-27T16:14:00.000-03:00</published><updated>2011-06-27T16:14:17.566-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='sbt'/><title type='text'>A very quick guide to project creation on SBT 0.10.0</title><content type='html'>&lt;a href="https://github.com/harrah/xsbt/wiki"&gt;SBT 0.10.0&lt;/a&gt; is out, and it is a very different beast at first. Aside from the need for retooling and relearning, it is a very big improvement.&lt;br /&gt;&lt;br /&gt;However, these minor differences can slow down things a bit. For one thing, previous versions of SBT asked if you wanted to create a project if run on an empty directory, and that does not happen anymore. Now it creates some stuff automatically, but other stuff -- project name, version, scala version, directory layout -- it doesn't. So, let's take a quick look on how to accomplish (roughly) the same tasks.&lt;br /&gt;&lt;br /&gt;In the example below, I named my SBT 0.10.0 script &lt;i&gt;xsbt&lt;/i&gt;, so that I could use the older 0.7.7 with projects that are not yet migrated.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;dcs@ayanami:~/github$ mkdir TestProject&lt;br /&gt;dcs@ayanami:~/github$ cd TestProject&lt;br /&gt;dcs@ayanami:~/github/TestProject$ xsbt&lt;br /&gt;Getting net.java.dev.jna jna 3.2.3 ...&lt;br /&gt;:: retrieving :: org.scala-tools.sbt#boot-app&lt;br /&gt; confs: [default]&lt;br /&gt; 1 artifacts copied, 0 already retrieved (838kB/35ms)&lt;br /&gt;Getting Scala 2.8.1 (for sbt)...&lt;br /&gt;:: retrieving :: org.scala-tools.sbt#boot-scala&lt;br /&gt; confs: [default]&lt;br /&gt; 4 artifacts copied, 0 already retrieved (15296kB/232ms)&lt;br /&gt;Getting org.scala-tools.sbt sbt_2.8.1 0.10.0 ...&lt;br /&gt;:: retrieving :: org.scala-tools.sbt#boot-app&lt;br /&gt; confs: [default]&lt;br /&gt; 34 artifacts copied, 0 already retrieved (6012kB/215ms)&lt;br /&gt;[info] Set current project to root (in build file:/home/dcs/.sbt/plugins/)&lt;br /&gt;[info] Set current project to default (in build file:/home/dcs/github/TestProject/)&lt;br /&gt;&gt; set name := "TestProject"&lt;br /&gt;[info] Reapplying settings...&lt;br /&gt;[info] Set current project to default (in build file:/home/dcs/github/TestProject/)&lt;br /&gt;&gt; set version := "1.0"&lt;br /&gt;[info] Reapplying settings...&lt;br /&gt;[info] Set current project to default (in build file:/home/dcs/github/TestProject/)&lt;br /&gt;&gt; set scalaVersion := "2.9.0-1"&lt;br /&gt;[info] Reapplying settings...&lt;br /&gt;Getting Scala 2.9.0-1 ...&lt;br /&gt;:: retrieving :: org.scala-tools.sbt#boot-scala&lt;br /&gt; confs: [default]&lt;br /&gt; 4 artifacts copied, 0 already retrieved (20447kB/186ms)&lt;br /&gt;[info] Set current project to default (in build file:/home/dcs/github/TestProject/)&lt;br /&gt;&gt; session save&lt;br /&gt;[info] Reapplying settings...&lt;br /&gt;[info] Set current project to default (in build file:/home/dcs/github/TestProject/)&lt;br /&gt;&gt; exit&lt;br /&gt;dcs@ayanami:~/github/TestProject$ find . -type d&lt;br /&gt;.&lt;br /&gt;./project&lt;br /&gt;./project/target&lt;br /&gt;./project/target/config-classes&lt;br /&gt;./project/target/scala_2.8.1&lt;br /&gt;./project/boot&lt;br /&gt;./project/boot/other&lt;br /&gt;./project/boot/other/net.java.dev.jna&lt;br /&gt;./project/boot/other/net.java.dev.jna/jna&lt;br /&gt;./project/boot/other/net.java.dev.jna/jna/3.2.3&lt;br /&gt;./project/boot/scala-2.9.0-1&lt;br /&gt;./project/boot/scala-2.9.0-1/lib&lt;br /&gt;./project/boot/scala-2.8.1&lt;br /&gt;./project/boot/scala-2.8.1/lib&lt;br /&gt;./project/boot/scala-2.8.1/org.scala-tools.sbt&lt;br /&gt;./project/boot/scala-2.8.1/org.scala-tools.sbt/sbt&lt;br /&gt;./project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.0&lt;br /&gt;./project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.0/compiler-interface-bin_2.7.7.final&lt;br /&gt;./project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.0/compiler-interface-src&lt;br /&gt;./project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.0/compiler-interface-bin_2.9.0.final&lt;br /&gt;./project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.0/compiler-interface-bin_2.8.1.final&lt;br /&gt;./project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.0/xsbti&lt;br /&gt;./target&lt;br /&gt;./target/streams&lt;br /&gt;./target/streams/$global&lt;br /&gt;./target/streams/$global/$global&lt;br /&gt;./target/streams/$global/$global/streams&lt;br /&gt;./target/streams/$global/$global/streams/$global&lt;br /&gt;dcs@ayanami:~/github/TestProject$ ls&lt;br /&gt;build.sbt  project  target&lt;br /&gt;dcs@ayanami:~/github/TestProject$ cat build.sbt&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;name := "TestProject"&lt;br /&gt;&lt;br /&gt;version := "1.0"&lt;br /&gt;&lt;br /&gt;scalaVersion := "2.9.0-1"&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;So far so good, but note that the directories for source are not created. The new version of SBT expects your IDE to do that (which is rather annoying for us vim users), or so it seems. However, the &lt;a href="https://github.com/typesafehub/sbteclipse"&gt;eclipse plugin&lt;/a&gt; can do that at the same time it creates the eclipse project. Here's an example:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;dcs@ayanami:~/github/TestProject$ cat ~/.sbt/plugins/build.sbt &lt;br /&gt;resolvers += {&lt;br /&gt;  val typesafeRepoUrl = new java.net.URL("http://repo.typesafe.com/typesafe/releases")&lt;br /&gt;  val pattern = Patterns(false, "[organisation]/[module]/[sbtversion]/[revision]/[type]s/[module](-[classifier])-[revision].[ext]")&lt;br /&gt;  Resolver.url("Typesafe Repository", typesafeRepoUrl)(pattern)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;libraryDependencies &lt;&lt;= (libraryDependencies, sbtVersion) { (deps, version) =&gt; &lt;br /&gt;  deps :+ ("com.typesafe.sbteclipse" %% "sbteclipse" % "1.1" extra("sbtversion" -&gt; version))&lt;br /&gt;}&lt;br /&gt;dcs@ayanami:~/github/TestProject$ xsbt&lt;br /&gt;[info] Compiling 1 Scala source to /home/dcs/.sbt/plugins/project/target/scala_2.8.1/classes...&lt;br /&gt;[info] Set current project to root (in build file:/home/dcs/.sbt/plugins/)&lt;br /&gt;[info] Compiling 8 Scala sources to /home/dcs/.sbt/staging/a69240767cc8e721757e/target/scala-2.8.1.final/classes...&lt;br /&gt;[info] Set current project to default (in build file:/home/dcs/github/TestProject/)&lt;br /&gt;&gt; eclipse create-src   &lt;br /&gt;[info] Updating...&lt;br /&gt;[info] Done updating.&lt;br /&gt;[info] Successfully created Eclipse project files. Please select the appropriate Eclipse plugin for Scala 2.9.0-1!&lt;br /&gt;&gt; exit&lt;br /&gt;dcs@ayanami:~/github/TestProject$ find . -type d&lt;br /&gt;.&lt;br /&gt;./project&lt;br /&gt;./project/target&lt;br /&gt;./project/target/config-classes&lt;br /&gt;./project/target/scala_2.8.1&lt;br /&gt;./project/boot&lt;br /&gt;./project/boot/other&lt;br /&gt;./project/boot/other/net.java.dev.jna&lt;br /&gt;./project/boot/other/net.java.dev.jna/jna&lt;br /&gt;./project/boot/other/net.java.dev.jna/jna/3.2.3&lt;br /&gt;./project/boot/scala-2.9.0-1&lt;br /&gt;./project/boot/scala-2.9.0-1/lib&lt;br /&gt;./project/boot/scala-2.8.1&lt;br /&gt;./project/boot/scala-2.8.1/lib&lt;br /&gt;./project/boot/scala-2.8.1/org.scala-tools.sbt&lt;br /&gt;./project/boot/scala-2.8.1/org.scala-tools.sbt/sbt&lt;br /&gt;./project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.0&lt;br /&gt;./project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.0/compiler-interface-bin_2.7.7.final&lt;br /&gt;./project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.0/compiler-interface-src&lt;br /&gt;./project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.0/compiler-interface-bin_2.9.0.final&lt;br /&gt;./project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.0/compiler-interface-bin_2.8.1.final&lt;br /&gt;./project/boot/scala-2.8.1/org.scala-tools.sbt/sbt/0.10.0/xsbti&lt;br /&gt;./target&lt;br /&gt;./target/streams&lt;br /&gt;./target/streams/$global&lt;br /&gt;./target/streams/$global/ivy-sbt&lt;br /&gt;./target/streams/$global/ivy-sbt/$global&lt;br /&gt;./target/streams/$global/ivy-configuration&lt;br /&gt;./target/streams/$global/ivy-configuration/$global&lt;br /&gt;./target/streams/$global/update&lt;br /&gt;./target/streams/$global/update/$global&lt;br /&gt;./target/streams/$global/project-descriptors&lt;br /&gt;./target/streams/$global/project-descriptors/$global&lt;br /&gt;./target/streams/$global/$global&lt;br /&gt;./target/streams/$global/$global/streams&lt;br /&gt;./target/streams/$global/$global/streams/$global&lt;br /&gt;./target/scala-2.9.0.1&lt;br /&gt;./target/scala-2.9.0.1/cache&lt;br /&gt;./target/scala-2.9.0.1/cache/update&lt;br /&gt;./src&lt;br /&gt;./src/main&lt;br /&gt;./src/main/resources&lt;br /&gt;./src/main/java&lt;br /&gt;./src/main/scala&lt;br /&gt;./src/test&lt;br /&gt;./src/test/resources&lt;br /&gt;./src/test/java&lt;br /&gt;./src/test/scala&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;That's it! I strongly recommend reading the wiki linked at the beginning of this post, but this will get you going for small stuff.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-358664946218534453?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/358664946218534453/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2011/06/very-quick-guide-to-project-creation-on.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/358664946218534453'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/358664946218534453'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2011/06/very-quick-guide-to-project-creation-on.html' title='A very quick guide to project creation on SBT 0.10.0'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-5347288083182843910</id><published>2011-05-21T12:49:00.000-03:00</published><updated>2011-05-21T12:49:45.307-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='scala 2.9'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Scala 2.9 optimizes for comprehensions way better!</title><content type='html'>Ok, I completely missed this. For comprehensions in Scala 2.9 was way better optimized with the parameter &lt;code&gt;-optimize&lt;/code&gt; than they were before! Take this code:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;class OptEx {&lt;br /&gt;    def sum(l: Array[Int]) = {&lt;br /&gt;        var acc = 0&lt;br /&gt;        for (i &lt;- 0 until l.length) acc += l(i)&lt;br /&gt;        acc&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;This is the java bytecode generated with Scala 2.8.1 for the method &lt;code&gt;sum&lt;/code&gt;:&lt;pre class="brush: text"&gt;public int sum(int[]);&lt;br /&gt;  Code:&lt;br /&gt;   0:   new     #7; //class scala/runtime/IntRef&lt;br /&gt;   3:   dup&lt;br /&gt;   4:   iconst_0&lt;br /&gt;   5:   invokespecial   #12; //Method scala/runtime/IntRef."&lt;init&gt;":(I)V&lt;br /&gt;   8:   astore_2&lt;br /&gt;   9:   new     #14; //class scala/runtime/RichInt&lt;br /&gt;   12:  dup&lt;br /&gt;   13:  iconst_0&lt;br /&gt;   14:  invokespecial   #15; //Method scala/runtime/RichInt."&lt;init&gt;":(I)V&lt;br /&gt;   17:  aload_1&lt;br /&gt;   18:  arraylength&lt;br /&gt;   19:  invokevirtual   #19; //Method scala/runtime/RichInt.until:(I)Lscala/collection/immutable/Range$ByOne;&lt;br /&gt;   22:  new     #21; //class OptEx$$anonfun$sum$1&lt;br /&gt;   25:  dup&lt;br /&gt;   26:  aload_0&lt;br /&gt;   27:  aload_1&lt;br /&gt;   28:  aload_2&lt;br /&gt;   29:  invokespecial   #24; //Method OptEx$$anonfun$sum$1."&lt;init&gt;":(LOptEx;[ILscala/runtime/IntRef;)V&lt;br /&gt;   32:  invokeinterface #30,  2; //InterfaceMethod scala/collection/immutable/Range$ByOne.foreach$mVc$sp:(Lscala/Functio&lt;br /&gt;n1;)V&lt;br /&gt;   37:  aload_2&lt;br /&gt;   38:  getfield        #34; //Field scala/runtime/IntRef.elem:I&lt;br /&gt;   41:  ireturn&lt;br /&gt;&lt;/pre&gt;And this is what Scala 2.9.0 does:&lt;pre class="brush: text"&gt;public int sum(int[]);&lt;br /&gt;  Code:&lt;br /&gt;   0:   new     #7; //class scala/runtime/IntRef&lt;br /&gt;   3:   dup&lt;br /&gt;   4:   iconst_0&lt;br /&gt;   5:   invokespecial   #12; //Method scala/runtime/IntRef."&lt;init&gt;":(I)V&lt;br /&gt;   8:   astore  6&lt;br /&gt;   10:  new     #14; //class scala/runtime/RichInt&lt;br /&gt;   13:  dup&lt;br /&gt;   14:  iconst_0&lt;br /&gt;   15:  invokespecial   #15; //Method scala/runtime/RichInt."&lt;init&gt;":(I)V&lt;br /&gt;   18:  aload_1&lt;br /&gt;   19:  arraylength&lt;br /&gt;   20:  istore_3&lt;br /&gt;   21:  astore_2&lt;br /&gt;   22:  getstatic       #21; //Field scala/collection/immutable/Range$.MODULE$:Lscala/collection/immutable/Range$;&lt;br /&gt;   25:  aload_2&lt;br /&gt;   26:  invokevirtual   #25; //Method scala/runtime/RichInt.self:()I&lt;br /&gt;   29:  iload_3&lt;br /&gt;   30:  invokevirtual   #29; //Method scala/collection/immutable/Range$.apply:(II)Lscala/collection/immutable/Range;&lt;br /&gt;   33:  dup&lt;br /&gt;   34:  astore  8&lt;br /&gt;   36:  invokevirtual   #34; //Method scala/collection/immutable/Range.length:()I&lt;br /&gt;   39:  iconst_0&lt;br /&gt;   40:  if_icmple       83&lt;br /&gt;   43:  aload   8&lt;br /&gt;   45:  invokevirtual   #37; //Method scala/collection/immutable/Range.last:()I&lt;br /&gt;   48:  istore  4&lt;br /&gt;   50:  aload   8&lt;br /&gt;   52:  invokevirtual   #40; //Method scala/collection/immutable/Range.start:()I&lt;br /&gt;   55:  istore  9&lt;br /&gt;   57:  iload   9&lt;br /&gt;   59:  iload   4&lt;br /&gt;   61:  if_icmpne       89&lt;br /&gt;   64:  iload   9&lt;br /&gt;   66:  istore  5&lt;br /&gt;   68:  aload   6&lt;br /&gt;   70:  aload   6&lt;br /&gt;   72:  getfield        #44; //Field scala/runtime/IntRef.elem:I&lt;br /&gt;   75:  aload_1&lt;br /&gt;   76:  iload   5&lt;br /&gt;   78:  iaload&lt;br /&gt;   79:  iadd&lt;br /&gt;   80:  putfield        #44; //Field scala/runtime/IntRef.elem:I&lt;br /&gt;   83:  aload   6&lt;br /&gt;   85:  getfield        #44; //Field scala/runtime/IntRef.elem:I&lt;br /&gt;   88:  ireturn&lt;br /&gt;   89:  iload   9&lt;br /&gt;   91:  istore  7&lt;br /&gt;   93:  aload   6&lt;br /&gt;   95:  aload   6&lt;br /&gt;   97:  getfield        #44; //Field scala/runtime/IntRef.elem:I&lt;br /&gt;   100: aload_1&lt;br /&gt;   101: iload   7&lt;br /&gt;   103: iaload&lt;br /&gt;   104: iadd&lt;br /&gt;   105: putfield        #44; //Field scala/runtime/IntRef.elem:I&lt;br /&gt;   108: iload   9&lt;br /&gt;   110: aload   8&lt;br /&gt;   112: invokevirtual   #47; //Method scala/collection/immutable/Range.step:()I&lt;br /&gt;   115: iadd&lt;br /&gt;   116: istore  9&lt;br /&gt;   118: goto    57&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Time to take your old benchmarks out of the closet, people!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-5347288083182843910?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/5347288083182843910/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2011/05/scala-29-optimizes-for-comprehensions.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/5347288083182843910'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/5347288083182843910'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2011/05/scala-29-optimizes-for-comprehensions.html' title='Scala 2.9 optimizes for comprehensions way better!'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-381833916152116443</id><published>2011-05-19T12:46:00.000-03:00</published><updated>2011-05-19T12:46:49.468-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='regex'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Regex Again</title><content type='html'>I have been thinking about regex lately. I have never felt comfortable with how Scala regex works, but I could never settle on what should be done about. Recently, I have started more and more of thinking of regex like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;class RegexF(pattern: String) extends String =&gt; Option[Seq[String]]&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;or, perhaps,&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;class RegexPF(pattern: String) extends PartialFunction[String, Seq[String]]&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;In fact, &lt;code&gt;RegexPF.lift&lt;/code&gt; would (could) yield a &lt;code&gt;RegexF&lt;/code&gt;. It then caught my attention that &lt;code&gt;RegexF.apply&lt;/code&gt; has the same signature as &lt;code&gt;Regex.unapplySeq&lt;/code&gt;, which is the standard way of handling regex in Scala!&lt;br /&gt;&lt;br /&gt;Might this be what has been bugging me about Scala's regex all along? Should we translate&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;val YYYYMMDD = """(\d{4})-(\d{2})-(\d{2})""".r&lt;br /&gt;val MMDDYYYY = """(\d{2})/(\d{2})/(\d{4})""".r&lt;br /&gt;&lt;br /&gt;def getYear(s: String) = s match {&lt;br /&gt;    case YYYYMMDD(year, _, _) =&gt; year&lt;br /&gt;    case MMDDYYYY(_, _, year) =&gt; year&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;into&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;val YYYYMMDD = """(\d{4})-(\d{2})-(\d{2})""".r&lt;br /&gt;val MMDDYYYY = """(\d{2})/(\d{2})/(\d{4})""".r andThen (fields =&gt; fields.last +: fields.init)&lt;br /&gt;&lt;br /&gt;def getYear(s: String) = ((YYYYMMDD orElse MMDDYYYY) andThen (_.head))(s)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;I can certainly see the advantages of pattern matching, but... it doesn't compose very well. And it has some performance issues, which is a big deal for most regex usages. And being a PartialFunction would not prevent a Regex from having extractors as well.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-381833916152116443?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/381833916152116443/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2011/05/regex-again.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/381833916152116443'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/381833916152116443'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2011/05/regex-again.html' title='Regex Again'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-5474412766782477980</id><published>2011-05-14T23:30:00.000-03:00</published><updated>2011-05-14T23:30:40.814-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='algorithm'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>A Cute Algorithm</title><content type='html'>These days I &lt;a href="http://analgorithmaday.blogspot.com/2011/05/find-k-th-minimum-in-two-sorted-array.html"&gt;read abou&lt;/a&gt;t an algorithm challenge: given two sorted arrays, find the k-th minimum element from their merge.&lt;br /&gt;&lt;br /&gt;Well, if you do merge them, you can just get the element at index k, and the merge can be done in O(n + m), where n and m are the respective size of each array.&lt;br /&gt;&lt;br /&gt;The solution given is O(k) and pretty simple: keep an index into each array, and increase one or other until you reach k. It can be done in O(log k), though, and, fortunately for me, my first idea on how to solve it in O(k) is more easily adaptable.&lt;br /&gt;&lt;br /&gt;My own O(k) version is like this: point an index at the k-th element on the first array, and another at the first element of the second array. If the element on the first array is smaller than the element on the first array, return that. Otherwise, as long as the element on the first array is bigger than the element on the second array, decrease the first index and increase the second. After doing that, you'll have the elements on each array that make up the k smallest elements, the k-th being the bigger between the top one in each array.&lt;br /&gt;&lt;br /&gt;In code, something like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;def kMin(a1: Array[Int], a2: Array[Int], k: Int) = {&lt;br /&gt;    def recurse(k2: Int): Int =&lt;br /&gt;        if (a1(k - k2 - 1) &amp;lt; a2(k2)) recurse(k2 + 1)&lt;br /&gt;        else k2&lt;br /&gt;&lt;br /&gt;    if (a1(k - 1) &amp;lt; a2(0)) a1(k - 1)&lt;br /&gt;    else {&lt;br /&gt;      val k2 = recurse(1)&lt;br /&gt;      a1(k - k2 - 1) max a2(k2 - 1)&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now, that code isn't particularly good, as there are some conditions that can break it. For instance, if the first array's size is smaller than k, you'll get an array index out of bounds exception. However, it gives the basis for explaining the O(k) algorithm.&lt;br /&gt;&lt;br /&gt;Here we search linearly for the k smallest elements of both arrays together, but we know these arrays are sorted. So, instead of going one by one, we can use &lt;i&gt;binary search&lt;/i&gt; instead, and turn it into O(log k)!&lt;br /&gt;&lt;br /&gt;The concept is simple.&amp;nbsp;We are looking into the k smallest elements of the two array together, so we know beforehand that the maximum number of elements we need to look into either array is k.&lt;br /&gt;&lt;br /&gt;We'll search one array for the biggest element that is smaller than or equal to the k-th minimum, with the upper bound being the k-th element of that array, and the lower bound being 0 (meaning the k smallest elements are all in the other array).&lt;br /&gt;&lt;br /&gt;To check if the number x-th is among the k-smallest ones, we see if that number is smaller than the (k - x)-th element on the other array. If it is, then x is among the k smallest. The intuitive explanation for that is that, if you take (k - x) elements from the one array and x elements from the other, you get exactly k elements. No element y &amp;gt; x in x's array will be smaller than x, since the array is sorted. And since the (k - x)-th element in the other array is also bigger than it, then no other element in the other array can be smaller either.&lt;br /&gt;&lt;br /&gt;So, as long as we find an element that belongs in the k-th smallest, we move the lower bound. If we find an element that does not belong in the k-th smallest, we move the upper bound below it.&lt;br /&gt;&lt;br /&gt;Once we find how many elements in one array belong in the k-smallest, we also know how many elements we must take from the other array. Pick the biggest among the biggest in each array, and you have the k-th smallest.&lt;br /&gt;&lt;br /&gt;Here's the code below, which is much more concise than the above explanation. It finds the k-th smallest element, with k=1 being the smallest element of all. It assumes there are at least k elements overall on the arrays, though k may be bigger than the number of elements on one array. In fact, either array may be empty (but not both).  One can find this code at my &lt;a href="https://github.com/dcsobral/kMin"&gt;github repository&lt;/a&gt;, along with an sbt project and a Scalacheck test case.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;    def kMin(a1: Array[Int], a2: Array[Int], k: Int): Int = {&lt;br /&gt;      def select(k2: Int) = k2 match {&lt;br /&gt;        case `k` =&amp;gt; a2(k - 1)&lt;br /&gt;        case 0   =&amp;gt; a1(k - 1)&lt;br /&gt;        case _   =&amp;gt; a1(k - k2 - 1) max a2(k2 - 1)&lt;br /&gt;      }&lt;br /&gt;      &lt;br /&gt;      def recurse(top: Int, bottom: Int): Int = {&lt;br /&gt;        if (top == bottom) select(top)&lt;br /&gt;        else {&lt;br /&gt;          val x = (bottom + top) / 2 max bottom + 1&lt;br /&gt;          if (a1(k - x) &amp;lt;= a2(x - 1)) recurse (x - 1, bottom)&lt;br /&gt;          else recurse(top, x)&lt;br /&gt;        }&lt;br /&gt;      }&lt;br /&gt;      &lt;br /&gt;      recurse(k min a2.size, 0 max k - a1.size)&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-5474412766782477980?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/5474412766782477980/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2011/05/cute-algorithm.html#comment-form' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/5474412766782477980'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/5474412766782477980'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2011/05/cute-algorithm.html' title='A Cute Algorithm'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-1623475585983456608</id><published>2011-05-12T14:52:00.000-03:00</published><updated>2011-05-13T17:35:07.488-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='parallel'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Scala 2.9 and Parallel collections</title><content type='html'>So, &lt;a href="http://www.scala-lang.org/node/9483"&gt;Scala 2.9.0&lt;/a&gt; is out. Also, the &lt;a href="http://typesafe.com/stack"&gt;Typesafe Stack&lt;/a&gt; is also out, which brings together Scala, Akka, and a few other things to get one up-and-running quickly. Much fun.&lt;br /&gt;&lt;br /&gt;On the collection side of things, one of the first questions I saw was: do parallel collections share a common interface with standard collections. The answer is yes, they do, but not one that existed in 2.8.1.&lt;br /&gt;&lt;br /&gt;You see, a trouble with parallel collections is that, now that they are available, people will probably be passing them around. If they could be passed to old code -- as it was briefly contemplated -- that old code could crash in mysterious ways. In fact, it happens with REPL itself.&lt;br /&gt;&lt;br /&gt;For that reason, ALL of your code comes with a &lt;i&gt;guarantee&lt;/i&gt; that it will only accept sequential collections. In other words, Iterable, Seq, Set, etc, they all now share a guarantee to be sequential, which means you cannot pass a parallel sequence to a method expecting Seq.&lt;br /&gt;&lt;br /&gt;The parallel collections start with Par: ParIterable, ParSeq, ParSet and ParMap. No ParTraversable for now. These are guaranteed to be parallel. They can be found inside scala.collection.parallel, scala.collection.parallel.immutable, etc.&lt;br /&gt;&lt;br /&gt;You can also get a parallel collection just by calling the ".par" method on it, and, similarly, the ".seq" method will return a sequential collection.&lt;br /&gt;&lt;br /&gt;Now, if you want your code to &lt;i&gt;not care&lt;/i&gt; whether it receives a parallel or sequential collection, you should prefix it with Gen: GenTraversable, GenIterable, GenSeq, etc. These can be either parallel or sequential.&lt;br /&gt;&lt;br /&gt;And, now, something fun to try out:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;def p[T](coll: collection.GenIterable[T]) = coll foreach println; p(1 to 20); p((1 to 20).par)&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-1623475585983456608?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/1623475585983456608/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2011/05/scala-29-and-parallel-collections.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/1623475585983456608'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/1623475585983456608'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2011/05/scala-29-and-parallel-collections.html' title='Scala 2.9 and Parallel collections'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-3659203143617959184</id><published>2011-04-30T23:02:00.000-03:00</published><updated>2011-04-30T23:02:46.208-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='beginner'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Expressive Code and the Alternative Vote</title><content type='html'>One of the joys of&amp;nbsp;writing&amp;nbsp;code in Scala is how expressive it looks. Instead of dealing with the minutia of handling data, I can concentrate on what the code is actually doing. With experienced Scala programmers, that goes without saying. Newcomers have a harder time, because they are still a bit confused by grammar and vocabulary to pay proper attention to what is being said, so to speak.&lt;br /&gt;&lt;br /&gt;The most striking example of that comes from the use of Scala's collection. There are many powerful collection libraries out there, but you are usually made very aware that you are handling a collection -- code to be hidden inside a class, to avoid contaminating business logic with it. Scala's collections, on the other hand, can easily fit in the highest abstraction levels of the code.&lt;br /&gt;&lt;br /&gt;Let me take an example from the upcoming British referendum about the adoption (or not) of &lt;a href="http://en.wikipedia.org/wiki/Instant-runoff_voting"&gt;Alternative Vote&lt;/a&gt;. In this voting system, each voter ranks the candidates in order of preference. Depending on the specifics of its implementation, it may be possible or not to leave candidates unranked. The winner is the candidate that manages to get 50% of the votes, with the the candidate with the least votes being removed and his or her votes being reassigned according to the voter's preferences until some candidate gets elected.&lt;br /&gt;&lt;br /&gt;So, let's consider how one could implement the algorithm that decides who the winner is. Let's say we have a set of candidates, identified by their names, and a list of votes. Each vote is a list of candidates ranked by preference. From that, we have to produce the name of the winner. In other words:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;def elect(candidates: Set[String], votes: Seq[Seq[String]]): String = {&lt;/pre&gt;&lt;br /&gt;So, where do we begin? There are three essential tasks: we need to tally the votes for every candidate, we need to see if the candidate with most votes has at least 50% of all votes, and we need to discover who's the candidate the the least amount of votes.&lt;br /&gt;&lt;br /&gt;Let's say we did these tasks, and now we know who the candidate with least and most votes are, and we have a tally of votes for all candidates.&amp;nbsp;In this case, we can return the winner very easily, if there's one:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;    if (votesByCandidate(mostVotesCandidate) &amp;gt;= votes.size / 2) mostVotesCandidate&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Which still leave us the problem of how to handle the (expected) usual case of no candidate reaching 50% on first tally. There's an easy solution for that, though: just remove the candidate with least votes from the pool of candidates, and try to get a winner out of that. It's easy, because we already have a function that does that:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;    else elect(candidates - leastVotesCandidate, votes)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Of the three tasks posed earlier, two are pretty simple as well: deciding who's the candidate with least and most votes. We could sort all candidates by vote and take the first and last candidate, but we don't actually need to &lt;i&gt;sort&lt;/i&gt;&amp;nbsp;anything: just knowing top and bottom is enough. We can do that like this:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;    val mostVotesCandidate = candidates maxBy votesByCandidate&lt;br /&gt;    val leastVotesCandidate = candidates minBy votesByCandidate&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now all that's left is finding how many votes each candidate has. We could pick the first preference in each vote and do a tally on that, but some candidates may have been removed from the pool. Instead let's say the &lt;i&gt;valid candidates&lt;/i&gt;&amp;nbsp;of a vote are the ranked list of candidates for a vote that are still in the running. We can compute that for a vote by doing:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;    def validCandidates(vote: Seq[String]): Seq[String] = vote filter candidates&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This doesn't read right, actually. A minor complain some people have about collection methods is that filter seems to do exactly the opposite of what's wanted: if you say filter X (those for which X is true), then it will &lt;i&gt;keep&lt;/i&gt;&amp;nbsp;X instead of discarding it. So, when we say "filter candidates", it will &lt;i&gt;keep&lt;/i&gt;&amp;nbsp;these candidates in the vote, and discard the rest.&lt;br /&gt;&lt;br /&gt;The other non-obvious thing about this line is "candidates" itself. What does it mean to say "filter candidates"? Well, "filter" takes a function which, given a value of the collection, will return true or false depending on whether that value must be kept or discarded. That means "candidates" must be a function which, given the name of a candidate, returns true or false.&lt;br /&gt;&lt;br /&gt;However, "candidates" is a set! We declared it so in the very first line of code presented, didn't we? Well, in Scala a set is &lt;i&gt;also&lt;/i&gt;&amp;nbsp;a function that tests whether a value is present in the set or not, returning true or false accordingly. In fact, sequences and maps are also functions in Scala, the former from indices to values, and the latter from keys to values.&lt;br /&gt;&lt;br /&gt;Well, enough about that. We can now just take the first candidate in the list of valid candidates and tally the votes... as long as all candidates are ranked in each vote. If that is not the case, then a vote may well not contain any candidates still in the running, in which case the list of valid candidates will be empty.&lt;br /&gt;&lt;br /&gt;Since this example comes from the British referendum, and the AV proposed in that referendum does not require votes to rank all candidates, we'll deal with that. Let's say the first valid candidate of a vote may be some candidate or no one. That is,&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;    def firstValidCandidate(vote: Seq[String]): Option[String] = validCandidates(vote) headOption&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;We can then use this to get a list of first choices for all votes with a valid first candidate:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;    val firstChoices = votes flatMap firstValidCandidate&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The votes for a candidate are the number of first choices for that candidate. We'll make a map out of it to avoid recounting that every time.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;    def votesFor(candidate: String) = firstChoices count (candidate ==)&lt;br /&gt;    val votesByCandidate = candidates map (candidate =&amp;gt; candidate -&amp;gt; votesFor(candidate)) toMap;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;Finally, we have to do something about the possibility of no candidate reaching 50%, which is possible in a system where not all candidates are ranked. I don't know how the proposed system will do in that case, but I'll just choose the most voted candidate if there aren't more than two.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;With that fix in, this is what the whole code looks like:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;pre class="brush: scala"&gt;def elect(candidates: Set[String], votes: Seq[Seq[String]]): String = {&lt;br /&gt;    def validCandidates(vote: Seq[String]): Seq[String] = vote filter candidates&lt;br /&gt;    def firstValidCandidate(vote: Seq[String]): Option[String] = validCandidates(vote) headOption&lt;br /&gt;    val firstChoices = votes flatMap firstValidCandidate&lt;br /&gt;    def votesFor(candidate: String) = firstChoices count (candidate ==)&lt;br /&gt;    val votesByCandidate = candidates map (candidate =&amp;gt; candidate -&amp;gt; votesFor(candidate)) toMap;&lt;br /&gt;&lt;br /&gt;    val mostVotesCandidate = candidates maxBy votesByCandidate&lt;br /&gt;    val leastVotesCandidate = candidates minBy votesByCandidate&lt;br /&gt;&lt;br /&gt;    if (votesByCandidate(mostVotesCandidate) &amp;gt;= votes.size / 2 || candidates.size &amp;lt;= 2) mostVotesCandidate&lt;br /&gt;    else elect(candidates - leastVotesCandidate, votes)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;While there's a Scala oddity here and there, the code is pretty clear for all that it is doing.&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-3659203143617959184?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/3659203143617959184/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2011/04/expressive-code-and-alternative-vote.html#comment-form' title='7 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/3659203143617959184'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/3659203143617959184'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2011/04/expressive-code-and-alternative-vote.html' title='Expressive Code and the Alternative Vote'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>7</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-6454220351720748501</id><published>2011-03-22T13:09:00.000-03:00</published><updated>2011-03-22T13:09:37.726-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Scala popularity</title><content type='html'>I had 5 posts in this blog throughout 2010 -- two in January, two in June. One post January of this year. Given that, I'm pretty sure no one follows my blog except, perhaps, as a forgotten automatic tracker of some sort.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Well... I decided to blog about something back on Sunday, which is a terrible day to blog something if you want hits. &lt;i&gt;Late&lt;/i&gt;&amp;nbsp;Sunday. Looking at statistics for Monday, though, I see that I have hit three times more hits than my previous record in a single day.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;It is a heartening indication of how much interest Scala is attracting nowadays.&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-6454220351720748501?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/6454220351720748501/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2011/03/scala-popularity.html#comment-form' title='9 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/6454220351720748501'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/6454220351720748501'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2011/03/scala-popularity.html' title='Scala popularity'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>9</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-2928436644610462540</id><published>2011-03-20T19:54:00.002-03:00</published><updated>2011-03-24T09:27:19.786-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='scala 2.9'/><title type='text'>On Scala 2.9's road...</title><content type='html'>I suspect a lot of people are eagerly waiting for the parallel collections on Scala 2.9. The thing is... it's just not &lt;i&gt;my&lt;/i&gt; thing. I like that it is being made available, but it's just not a pervasive feature for my small&amp;nbsp;daily&amp;nbsp;needs.&lt;br /&gt;&lt;br /&gt;So, while I was somewhat bored by Scala 2.9, after the huge jump 2.8 was, there &lt;i&gt;has&lt;/i&gt;&amp;nbsp;been some nice improvements. For one thing, the jLine library used by REPL was replaced with one based on &lt;a href="https://github.com/jdillon/jline2"&gt;this&lt;/a&gt;&amp;nbsp;(the canonical repository to the jLine actually used in Scala is &lt;a href="https://github.com/paulp/jline2"&gt;here&lt;/a&gt;)&amp;nbsp;giving a much superior experience. Now one can edit input that spans multiple lines (longer than the number of columns in the screen) without trouble, search the history, etc. There's even something to show its key-bindings: just type &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;:keybindings&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;And speaking of REPL, it doesn't stop there, by a long margin! There's &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;:javap&lt;/span&gt;, which will&amp;nbsp;happily&amp;nbsp;decompile a class or file, &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;:type&lt;/span&gt; which will show an expression's type without evaluating it, and &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;:implicits&lt;/span&gt; to show what implicits are in scope. Add &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;-v&lt;/span&gt; to that last one, and it will show those that come with &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;Predef&lt;/span&gt; by default.&lt;br /&gt;&lt;br /&gt;Those of you pasting code into REPL, or wanting to define companion objects, or pretty much any other feature that depends on the content of the next line, you'll be happy to know there's now &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;:paste&lt;/span&gt;. Instead of instantly evaluating each line, it will wait until you hit &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;^D&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;More recently, a few features came up that will help those that like to do Scala scripting. The &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;-absolute-cp&lt;/span&gt; parameter will ensure relative paths on classpaths will be made absolute based on where the script is being run from, not where the compilation daemon was started at. If you don't even know what I'm talking about, then trust me: that will save you a lot of pain.&lt;br /&gt;&lt;br /&gt;Another option, &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;-max-idle&lt;/span&gt;, will let you specify how long the compilation daemon will stay up when idle, and even disable its auto-shutdown.&lt;br /&gt;&lt;br /&gt;And just to make scripting even nicer, &lt;a href="http://code.google.com/p/simple-build-tool/"&gt;SBT's &lt;/a&gt;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;Process &lt;/span&gt;library is now available in Scala, as &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;sys.process&lt;/span&gt;! Now we can do stuff like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;import sys.process._&lt;br /&gt;&lt;br /&gt;Process cat new URL("http://databinder.net/dispatch/About") !&lt;br /&gt;&lt;/pre&gt;&lt;pre class="brush: scala"&gt;"find src -name *.scala -exec grep null {} ;"  #|  "xargs test -z"  #&amp;amp;&amp;amp;  "echo null-free"  #||  "echo null detected"  !&lt;/pre&gt;&lt;br /&gt;Another interesting scripting feature is that not only will files containing a single object with a main method be runnable as if it were a script, but jar files produced by scala when it compiles scripts will be runnable like programs. For example:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;% cat script.scala&lt;br /&gt;object FiddleDeeMain {&lt;br /&gt;  def main(args: Array[String]): Unit = {&lt;br /&gt;    println(args mkString " ")&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;% scala -nocompdaemon script.scala a b c&lt;br /&gt;a b c&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;And, conversely,&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;% cat script2.scala&lt;br /&gt;println(args mkString " ")&lt;br /&gt;&lt;br /&gt;% scala -save script2.scala arg1 arg2&lt;br /&gt;arg1 arg2&lt;br /&gt;&lt;br /&gt;% scala script2.jar arg1 arg2&lt;br /&gt;arg1 arg2&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;On the library side, a few things have happened too. Some changes where made to &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;view&lt;/span&gt;, which made it much faster than it used to be. Arguably, its previous lack of performance resulted from a bug, so if you had performances issues with it, you might want to check it out again. Also on the performance front, another change with lots of potential is the introduction of a new hash code algorithm -- murmur3.&lt;br /&gt;&lt;br /&gt;To those of you who like writing methods and classes with &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;Numeric&lt;/span&gt; and &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;Ordering&lt;/span&gt;, you'll probably like to know that you can now add "&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;import Numeric.Implicits._&lt;/span&gt;" and "&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;import Ordering.Implicits._&lt;/span&gt;" and avoid all that messy implicit parameter handling. For example:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;import Numeric.Implicits._&lt;br /&gt;&lt;br /&gt;def sum[N: Numeric](lst: List[N]) = lst reduceLeft (_ + _)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;It might not seem much for a single method like that, but if you use this stuff often, I'm sure you see the advantages.&lt;br /&gt;&lt;br /&gt;There are plenty of small changes that will make life easier, or more intuitive. For example, &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;-5.abs&lt;/span&gt; will now work. Scaladoc is much faster. Many bugs have been fixed, even on places you'd never guess there were bugs (scary thought).&lt;br /&gt;&lt;br /&gt;An interesting improvement is the introduction of &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;DelayedInit&lt;/span&gt;. While most people won't ever hear of it -- unless it starts getting used in DSLs --, it enabled the rehabilitation&amp;nbsp;of a much criticized feature: the &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;Application &lt;/span&gt;trait. It is not that &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;Application&amp;nbsp;&lt;/span&gt;was a bad idea, but it was badly implemented. Given all that has been written about staying away from it, its new implementation was also given a new name, which we can now start using in our blogs everywhere: &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;App&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;On the realm of experimental stuff that may never make 2.9 at all, I'm pretty fond of&amp;nbsp;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;-Yrich-exceptions&lt;/span&gt;. It adds some capabilities to exceptions on REPL. One example is&amp;nbsp;&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;lastException.show&lt;/span&gt;, which will display the source code location of the exception, if available (to use it, point &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;"&gt;SOURCEPATH &lt;/span&gt;to the source code).&lt;br /&gt;&lt;br /&gt;There are plenty of other improvements, way too many to talk about: better docs, better error messages, better performance, bug fixes, more methods, new traits and classes, not to mention improvements made for people creating compiler plugins or working on Scala itself. If you want to get more dibs into Scala 2.9, there's a &lt;a href="https://sites.google.com/site/scalatohoku/changes-and-improvements-on-scala-2-9"&gt;japanese site tracking the changes&lt;/a&gt;, though only looking through the commit log one can truly feel the scope of what Scala 2.9 is. Kudos to Scala's development team!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-2928436644610462540?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/2928436644610462540/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2011/03/on-scala-29s-road.html#comment-form' title='12 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/2928436644610462540'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/2928436644610462540'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2011/03/on-scala-29s-road.html' title='On Scala 2.9&apos;s road...'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>12</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-5423806446610521895</id><published>2011-01-24T17:21:00.000-02:00</published><updated>2011-01-24T17:21:56.405-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Testing with Scala for Fun and Profit</title><content type='html'>Sometimes I like Scala, and sometimes I &lt;i&gt;really&lt;/i&gt;&amp;nbsp;like Scala.&lt;br /&gt;&lt;br /&gt;So, I was writing some algorithms to compute the median of a sequence of values, just for the fun of it, adapting from pseudo-code description of an algorithm. The problem with pseudo-code is that it is pseudo-precise, meaning my algorithm was pseudo-correct, so I wanted to test it to ensure it really worked.&lt;br /&gt;&lt;br /&gt;As it happens, the median of values has a trivial implementation that could be used to test against. So, one import and one one-liner afterwards, I had a quick way to test it from the REPL, where I could then experiment with the failing test case to understand what went wrong:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;import org.scalacheck.Prop._&lt;br /&gt;forAll((lst: List[Double]) =&amp;gt; lst.nonEmpty ==&amp;gt; (myAlgorithm(lst) == lst.sorted.apply((lst.size - 1) / 2))).check&lt;/pre&gt;&lt;br /&gt;That uses the &lt;a href="http://code.google.com/p/scalacheck/"&gt;Scalacheck&lt;/a&gt; library, the best way to test algorithms in my opinion. What I'm doing with &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;forAll&lt;/span&gt; is saying that for all inputs (&lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;List[Double]&lt;/span&gt;) of that function, the conditions must hold true. Specifically, if the input is not empty, then the result of my algorithm must be equal to the result of the trivial implementation of median. That will result in a &lt;i&gt;property&lt;/i&gt;&amp;nbsp;(class &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;Prop&lt;/span&gt;&lt;span class="Apple-style-span" style="font-family: inherit;"&gt;).&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;I then tell it to &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;check&lt;/span&gt; that property, which will be done by automatically generating input, with some heuristics to improve the chance of catching boundary cases, and testing the condition for each such input. If 100 tests pass, it finishes by saying:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;+ OK, passed 100 tests.&lt;/pre&gt;&lt;br /&gt;Or, if it fail at some point, it will say something like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;! Falsified after 0 passed tests.                                             &lt;br /&gt;&amp;gt; ARG_0: List("-1.0") (orig arg: List("-1.0", "8.988465674311579E307"))&lt;/pre&gt;&lt;br /&gt;To be honest, my one-liner was slightly longer, because I was using arrays and arrays in Java do not have a useful &lt;span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace; font-size: x-small;"&gt;toString&lt;/span&gt; method, so I had to tell Scalacheck how to print the array. Both Scalatest and Specs support integration with Scalacheck too, so this can be easily turned into part of a test suite.&lt;br /&gt;&lt;br /&gt;Now this helped me achieve correctness, but I was also interested in how fast the code could run. I had three different algorithms (including the trivial implementation), and two of them could be further refined by abstracting over the selection of a pivot (quicksort-style). At that point, I decided to build a small framework which would help me test everything automatically.&lt;br /&gt;&lt;br /&gt;I wanted to test each algorithm three times for different input sizes. The basic measurement algorithm was done by one of the methods in my toolkit:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;import java.lang.System.currentTimeMillis&lt;br /&gt;&lt;br /&gt;def bench[A](n: Int)(body: =&amp;gt; A): Long = {&lt;br /&gt;  val start = currentTimeMillis()&lt;br /&gt;  1 to n foreach { _ =&amp;gt; body }&lt;br /&gt;  currentTimeMillis() - start&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;This should be familiar to anyone who ever did microbenchmarking with Scala. With that in hand, another one liner got the results I wanted:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;println(bench(50000)(myAlgorithm(Array.fill(500)(nextDouble))))&lt;/pre&gt;&lt;br /&gt;Which worked well enough for a while, but really didn't scale as I got more algorithm variations and tested them with different settings. So, to get the results for each algorithm, I wrote this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;import scala.util.Random.nextDouble&lt;br /&gt;&lt;br /&gt;def benchmark(algorithm: Array[Double] =&amp;gt; Double,&lt;br /&gt;              arraySizes: List[Int]): List[Iterable[Long]] = &lt;br /&gt;    for (size &amp;lt;- arraySizes)&lt;br /&gt;    yield for (iteration &amp;lt;- 1 to 3)&lt;br /&gt;        yield bench(50000)(algorithm(Array.fill(size)(nextDouble)))&lt;/pre&gt;&lt;br /&gt;Which let me pass a list of sizes I wanted to test the stuff at, and run each benchmark three times, to give me a feel for the variation in the results. Next, I made a list of the algorithms I wanted tested:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;val algorithms = sortingAlgorithm :: immutableAlgorithms&lt;/pre&gt;&lt;br /&gt;That's the list I started with, but it grew as I added other algorithms. As for the immutable algorithms, they were all the same method call, but passing different pivot selection as parameters. As it got a bit verbose, I decided to apply a bit of DRY. First, I made a list of my pivot selection algorithms:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;val immutablePivotSelection: List[(String, Array[Double] =&amp;gt; Double)] = List(&lt;br /&gt;    "Random Pivot"      -&amp;gt; chooseRandomPivot,&lt;br /&gt;    "Median of Medians" -&amp;gt; medianOfMedians,&lt;br /&gt;    "Midpoint"          -&amp;gt; ((arr: Array[Double]) =&amp;gt; arr((arr.size - 1) / 2))&lt;br /&gt;)&lt;/pre&gt;&lt;br /&gt;Next, I used that list to produce a list of median algorithms using each of these pivot selections:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;val immutableAlgorithms = for ((name, pivotSelection) &amp;lt;- immutablePivotSelection)&lt;br /&gt;        yield name -&amp;gt; (findMedian(_: Array[Double])(pivotSelection))&lt;/pre&gt;&lt;br /&gt;With the list of algorithms in hand, it was a simple for comprehension to produce a list of results:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;val benchmarkResults: List[String] = for {&lt;br /&gt;    (name, algorithm) &amp;lt;- algorithms&lt;br /&gt;    results &amp;lt;- benchmark(algorithm, arraySizes).transpose&lt;br /&gt;} yield formattingString format (name, formatResults(results))&lt;/pre&gt;&lt;br /&gt;The transposition let me see each size on a different column, making it easier to compare the algorithms when displayed together. Anyway, once I had that ready, I could also easily use the list of algorithms to test them:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;def test(algorithm: Array[Double] =&amp;gt; Double, &lt;br /&gt;         reference: Array[Double] =&amp;gt; Double): String = {&lt;br /&gt;    def prettyPrintArray(arr: Array[Double]) = arr mkString ("Array(", ", ", ")")&lt;br /&gt;    val resultEqualsReference = forAll { (arr: Array[Double]) =&amp;gt; &lt;br /&gt;        arr.nonEmpty ==&amp;gt; (algorithm(arr) == reference(arr)) :| prettyPrintArray(arr)&lt;br /&gt;    }&lt;br /&gt;    Test.check(Test.Params(), resultEqualsReference)(Pretty.Params(verbosity = 0))&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;val testResults = for ((name, algorithm) &amp;lt;- algorithms)&lt;br /&gt;    yield formattingString format (name, test(algorithm, sortingAlgorithm._2))&lt;/pre&gt;&lt;br /&gt;I could even make the test method more general, but parameterizing the type of the algorithm, and adding a parameter for a no-parameter function generating the input. This could be easily done, but it was not needed by the time I was finished.&lt;br /&gt;&lt;br /&gt;I find the final result of a certain elegance (then again, I'm obviously biased), that's not the reason I really like Scala. What I really, really like about it, is how I could start very small, with a few easy commands on the REPL, and then use that as the basis for an increasingly more flexible framework to do the tests I wanted.&lt;br /&gt;&lt;br /&gt;If anyone is interested in seeing the full code, it can be found &lt;a href="http://stackoverflow.com/questions/4662292/scala-median-implementation/4663557#4663557"&gt;here&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-5423806446610521895?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/5423806446610521895/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2011/01/testing-with-scala-for-fun-and-profit.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/5423806446610521895'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/5423806446610521895'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2011/01/testing-with-scala-for-fun-and-profit.html' title='Testing with Scala for Fun and Profit'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-7098879896105753870</id><published>2010-12-23T23:25:00.002-02:00</published><updated>2010-12-23T23:56:25.139-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Sieve of Eratosthenes (the real one) Scala One-Liner</title><content type='html'>Here's a cute Sieve of Eratosthenes one liner (which I'm posting mostly so I won't loose it again):&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;(n: Int) =&gt; (2 to n) |&gt; (r =&gt; r.foldLeft(r.toSet)((ps, x) =&gt; if (ps(x)) ps -- (x * x to n by x) else ps))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;It requires the forward pipe operator, such as the one provided by &lt;a href="http://code.google.com/p/scalaz/"&gt;Scalaz&lt;/a&gt; or the one defined &lt;a href="http://stevegilham.blogspot.com/2009/01/pipe-operator-in-scala.html"&gt;here&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-7098879896105753870?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/7098879896105753870/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2010/12/sieve-of-eratosthenes-real-one-scala.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/7098879896105753870'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/7098879896105753870'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2010/12/sieve-of-eratosthenes-real-one-scala.html' title='Sieve of Eratosthenes (the real one) Scala One-Liner'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-9124392334477770320</id><published>2010-06-18T14:41:00.004-03:00</published><updated>2010-06-18T15:35:15.240-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='type class'/><category scheme='http://www.blogger.com/atom/ns#' term='beginner'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Type Class pattern example</title><content type='html'>I was pleasantly suprised by the popularity of my last article, but some people expressed the wish to see a more practical example, outside Scala library. It is always difficult to use practical examples in blog articles, as they often require a lot of context to be properly understood and introduce a lot of unnecessary complexity.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So I'm going to compromise here. The example below discuss a common task in many systems, but which I'm going to present in a very simplistic manner. Specifically, how to format stuff for output.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;There is much discussion about the proper place to handle output formatting. On one hand, for instance, we have the &lt;i&gt;toString &lt;/i&gt;method available on every Java object. It is not uncommon to have serializer, &lt;i&gt;toXML&lt;/i&gt;, or similar stuff either. On the other hand, such approach is not scalable and mixes business rules with presentation concerns, and architectures such as Model-View-Controller try to avoid it.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So let's try to solve this problem using the type class pattern. First, let's create or type class for a formatter which produces XML output (NodeSeq class), just as described in the last article. This time, there is one method we want this type class to have, though. Here it is:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;import scala.xml.NodeSeq&lt;br /&gt;&lt;br /&gt;abstract class FormatterXML[T] {&lt;br /&gt;  def format(input: T): NodeSeq&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;To test it, we'll create a very simple method that takes this type class and use it to print stuff to the console.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;def output[T](what: T)(implicit formatter: FormatterXML[T]) = println(formatter.format(what))&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;And, to finish the initial example, we'll create a simple class, good old Person, to test it. We'll put the implicit type class object inside the companion object of Person, so that it can be found automatically. Already, the class Person has become free of concerns about formatting, though companion object might be too close for some. This, however, is not necessary, as we'll see later.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;In the code below, as in other examples later on, I'm declaring the case class and the companion object in the same line, so that it can be easily pasted on REPL (which won't recognize the companion object as a companion object otherwise). I added a test line too at the end.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;case class Person(name: String, age: Int); object Person {&lt;br /&gt;  implicit object Formatter extends FormatterXML[Person] {&lt;br /&gt;    def format(input: Person): NodeSeq = &amp;lt;Person&gt;&amp;lt;Name&gt;{input.name}&amp;lt;/Name&gt;&amp;lt;Age&gt;{input.age}&amp;lt;/Age&gt;&amp;lt;/Person&gt;&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;output(Person("John", 32))&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So far, this can be trivially done in other ways, so we are gaining nothing. We'll gradually increase the complexity so that benefits of this approach start to show up. First, we'll create a Song class which has a Person member, so that we show off composition of the formatter.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;case class Song(title: String, author: Person); object Song {&lt;br /&gt;  implicit object Formatter extends FormatterXML[Song] {&lt;br /&gt;    def format(input: Song): NodeSeq = &amp;lt;Song&gt;&lt;br /&gt;      &amp;lt;Title&gt;{input.title}&amp;lt;/Title&gt;&lt;br /&gt;      &amp;lt;Author&gt;{implicitly[FormatterXML[Person]].format(input.author)}&amp;lt;/Author&gt;&lt;br /&gt;    &amp;lt;/Song&gt;&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;output(Song("War Pigs", Person("Ozzy Osbourne", 61)))&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now, I'm sure all of you must be up in arms right now, because, as everyone knows, Ozzy Osbourne wasn't the sole author of War Pigs. We need to change the Song class to accomodate more authors, but that will make the formatter more complex. To help us here, let's create a formatter for generic lists, that we can use to simplify the Song formatter:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;def ListFormatterXML[T](implicit formatter: FormatterXML[T]) = new FormatterXML[Traversable[T]] {&lt;br /&gt;  def format(input: Traversable[T]): NodeSeq = &amp;lt;List&gt;{input map formatter.format}&amp;lt;/List&gt;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Here we start to see an advantage to this approach. This method will work for any list (any traversable, in fact!), &lt;i&gt;as long as there is a formatter for its members&lt;/i&gt;. Anyway, let's see the Song again:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;case class Song(title: String, authors: Person*); object Song {&lt;br /&gt;  implicit object Formatter extends FormatterXML[Song] {&lt;br /&gt;    def format(input: Song): NodeSeq = &amp;lt;Song&gt;&lt;br /&gt;      &amp;lt;Title&gt;{input.title}&amp;lt;/Title&gt;&lt;br /&gt;      &amp;lt;Authors&gt;{ListFormatterXML[Person].format(input.authors)}&amp;lt;/Authors&gt;&lt;br /&gt;    &amp;lt;/Song&gt;&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;output(Song("War Pigs", &lt;br /&gt;            Person("Tony Iommi", 62), &lt;br /&gt;            Person("Ozzy Osbourne", 61), &lt;br /&gt;            Person("Geezer Butler", 60),&lt;br /&gt;            Person("Bill Ward", 62)))&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This works, but having &lt;i&gt;&lt;list&gt;&lt;/i&gt; as the sole child of &lt;i&gt;&lt;authors&gt;&lt;/i&gt; looks a bit weird. Let's do away with this:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;def ListFormatterXML[T](kind: String)(implicit formatter: FormatterXML[T]) = new FormatterXML[Traversable[T]] {&lt;br /&gt;  def format(input: Traversable[T]): NodeSeq = &amp;lt;List&gt;{input map formatter.format}&amp;lt;/List&gt;.copy(label = kind)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;case class Song(title: String, authors: Person*); object Song {&lt;br /&gt;  implicit object Formatter extends FormatterXML[Song] {&lt;br /&gt;    def format(input: Song): NodeSeq = &amp;lt;Song&gt;&lt;br /&gt;      &amp;lt;Title&gt;{input.title}&amp;lt;/Title&gt;&lt;br /&gt;      {ListFormatterXML[Person]("Authors").format(input.authors)}&lt;br /&gt;    &amp;lt;/Song&gt;&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;output(Song("War Pigs", &lt;br /&gt;            Person("Tony Iommi", 62), &lt;br /&gt;            Person("Ozzy Osbourne", 61), &lt;br /&gt;            Person("Geezer Butler", 60),&lt;br /&gt;            Person("Bill Ward", 62)))&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Personally, I like this better, but your milleage may vary. Anyway, let's increase complexity a bit. If we want scalability, we'd better make the formatter more flexible, able to handle many different formats. Let's redefine our type class, in a way that avoids changes to the code we have written so far:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;abstract class Formatter[T, Format] {&lt;br /&gt;  def format(input: T): Format&lt;br /&gt;} &lt;br /&gt;&lt;br /&gt;abstract class FormatterXML[T] extends Formatter[T, NodeSeq] {&lt;br /&gt;  def format(input: T): NodeSeq&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;We also need a new &lt;i&gt;output&lt;/i&gt;, but here we have a problem. How do we specify the format type explicitly while, at the same time, inferring the input type? I'll confess not having given much thought to this problem, but the following code will work:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;def as[F] = new {&lt;br /&gt;  def output[T](what: T)(implicit formatter: Formatter[T, F]) = println(formatter.format(what))&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;With this new definition in place, we can recompile Person, Song and ListFormatterXML above, and try it out like this:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;as[NodeSeq].output(Song("War Pigs", &lt;br /&gt;            Person("Tony Iommi", 62), &lt;br /&gt;            Person("Ozzy Osbourne", 61), &lt;br /&gt;            Person("Geezer Butler", 60),&lt;br /&gt;            Person("Bill Ward", 62)))&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;And, without changing any of that code, let's add a new output format to conclude this article:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;implicit object PersonFormatterString extends Formatter[Person, String] {&lt;br /&gt;  def format(input: Person): String = "%s, age %d" format (input.name, input.age)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;def ListFormatterString[T](kind: String)(implicit formatter: Formatter[T, String]) = new Formatter[Traversable[T], String] {&lt;br /&gt;  def format(input: Traversable[T]): String = input map formatter.format mkString (kind+" ", ", ", "; ")&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;implicit object SongFormatterString extends Formatter[Song, String] {&lt;br /&gt;  def format(input: Song): String = input.title+" "+ListFormatterString[Person]("by").format(input.authors)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;as[String].output(Song("War Pigs", &lt;br /&gt;            Person("Tony Iommi", 62), &lt;br /&gt;            Person("Ozzy Osbourne", 61), &lt;br /&gt;            Person("Geezer Butler", 60),&lt;br /&gt;            Person("Bill Ward", 62)))&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-9124392334477770320?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/9124392334477770320/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2010/06/type-class-pattern-example.html#comment-form' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/9124392334477770320'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/9124392334477770320'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2010/06/type-class-pattern-example.html' title='Type Class pattern example'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-5275064662786515343</id><published>2010-06-17T20:19:00.009-03:00</published><updated>2010-06-17T23:05:20.139-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='type class'/><category scheme='http://www.blogger.com/atom/ns#' term='beginner'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Implicit tricks -- the Type Class pattern</title><content type='html'>Some people have been recently discovering the Scala equivalent of Haskell's &lt;a href="http://en.wikipedia.org/wiki/Type_class"&gt;Type Classes&lt;/a&gt;. I was a bit suprised because I thought everyone with enough Scala experience already knew about them, but, apparently, I was wrong.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;A type class is basically a way to classify types based on the methods they offer. It offers an alternative to inheritance, in that you can group many different classes (types) that share a common set of methods, just like a superclass can be used to group its subclasses.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;While Scala does not support type classes directly, the same patterns that hold true for Haskell can be simulated by using implicits in Scala. Perhaps a bit improperly, Scala programmers have been calling this pattern "type classes" as well.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;It will feature proeminently in Scala 2.8, where examples can be found with &lt;a href="http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library/scala/math/Numeric.html"&gt;Numeric&lt;/a&gt;, &lt;a href="http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library/scala/math/Ordering.html"&gt;Ordering&lt;/a&gt; and even, I think, &lt;a href="http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library/scala/collection/generic/CanBuildFrom.html"&gt;CanBuildFrom&lt;/a&gt;. In fact, one can find &lt;a href="http://stackoverflow.com/search?q=[scala]+Numeric"&gt;many questions&lt;/a&gt; on Stack Overflow related to Numeric being used precisely as a type class.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, let me give a simple example of the kind of usage this can be put to. This is something someone just asked me on the #Scala channel on IRC, and I decided it makes for a nice example.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The problem put to me was restricting the options of a type parameter T without resorting to inheritance. For instance, if I want a method to work for Long and Int, but not any other type, there is no way to express that through a superclass. But the type class pattern can be used to solve it!&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Here is the idea: I'll create an abstract class that will represent my type class. I'll then create elements representing the classes belonging to that type class. Finally, I'll use an implicit parameter to restrict my type parameter to that type class.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;First, my abstract class:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;abstract class Acceptable[T]&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Yes, that's it. Not much to it, is there? Well, most often I would add to that class the methods I wish that type class to have. For instance, Numeric have all the normal operators you'd expect from classes that represent numbers. In this case, however, that won't be necessary, so I'm keeping it simple.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Next, let me create the members of my type class. I wish to create two of them: one for Int, and another for Long. To make them available without need for any import statements, I'll put them inside the companion class to Acceptable. Also, note that they are implicits.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;object Acceptable {&lt;br /&gt;  implicit object IntOk extends Acceptable[Int]&lt;br /&gt;  implicit object LongOk extends Acceptable[Long]&lt;br /&gt;}&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Little to it, right? So, how do I get to use it? Well, let's create a simple method that will only accept Int and Long, as we wanted:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;def f[T: Acceptable](t: T) = t&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;That weird declaration of T is called a &lt;i&gt;context bound&lt;/i&gt; in Scala lingo. It's new to Scala 2.8, precisely to make this stuff easier. What it actually does is automatically define an implicit parameter -- and, for that very reason, it cannot be combined with &lt;i&gt;other&lt;/i&gt; implicit parameters, though you can always use the full syntax to get the same result. Here's the full syntax:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;def f[T](t: T)(implicit ev: Acceptable[T]) = t&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, does it work? Well, here is a small session using it:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala"&gt;scala&gt; f(1)&lt;br /&gt;res0: Int = 1&lt;br /&gt;&lt;br /&gt;scala&gt; f(1L)&lt;br /&gt;res1: Long = 1&lt;br /&gt;&lt;br /&gt;scala&gt; f(1.0)&lt;br /&gt;&amp;lt;console&gt;:8: error: could not find implicit value for parameter ev: Acceptable[Double]&lt;br /&gt;       f(1.0)&lt;br /&gt;        ^&lt;br /&gt;&lt;br /&gt;scala&gt; f(1: Byte)&lt;br /&gt;&amp;lt;console&gt;:8: error: could not find implicit value for parameter ev: Acceptable[Byte]&lt;br /&gt;       f(1: Byte)&lt;br /&gt;        ^&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now, to those of you who may think this is neat but of little use, I'll point you to two examples of its usage in the new collections: the methods &lt;i&gt;sum &lt;/i&gt;and &lt;i&gt;max&lt;/i&gt;. If you try to call &lt;i&gt;sum &lt;/i&gt;on a list of things that are not Numeric, it won't work -- at compile time. Likewise, if you try &lt;i&gt;max &lt;/i&gt;on a list of things for which there are no Ordering available, it won't compile either. This way, these methods could be safely added to the collections without resorting to throwing exceptions at run-time!&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This is just little window into what is possible -- enough to get a hang on the pattern without risking information overload. But look around, as there is much more to it!&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-5275064662786515343?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/5275064662786515343/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2010/06/implicit-tricks-type-class-pattern.html#comment-form' title='9 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/5275064662786515343'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/5275064662786515343'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2010/06/implicit-tricks-type-class-pattern.html' title='Implicit tricks -- the Type Class pattern'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>9</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-5095388308494787145</id><published>2010-01-26T01:05:00.006-02:00</published><updated>2010-04-07T17:09:50.689-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='regex'/><category scheme='http://www.blogger.com/atom/ns#' term='beginner'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>String interpolation in Scala with Regex</title><content type='html'>Some new stuff I was waiting for has arrived on Scala. We can now have a limited form of string interpolation very easily:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;def interpolate(text: String, vars: Map[String, String]) =&lt;br /&gt;  """\$\{([^}]+)\}""".r.replaceAllIn(text, (_: scala.util.matching.Regex.Match) match { &lt;br /&gt;    case Regex.Groups(v) =&gt; vars.getOrElse(v, "") &lt;br /&gt;  })&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Which can then be used like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; "The ${name} of the ${game}"&lt;br /&gt;res0: java.lang.String = The ${name} of the ${game}&lt;br /&gt;&lt;br /&gt;scala&gt; Map("name" -&gt; "X", "game" -&gt; "Y")&lt;br /&gt;res1: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(name -&gt; X, game -&gt; Y)&lt;br /&gt;&lt;br /&gt;scala&gt; interpolate(res0, res1)&lt;br /&gt;res2: String = The X of the Y&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-5095388308494787145?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/5095388308494787145/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2010/01/string-interpolation-in-scala-with.html#comment-form' title='12 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/5095388308494787145'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/5095388308494787145'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2010/01/string-interpolation-in-scala-with.html' title='String interpolation in Scala with Regex'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>12</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-8031554644693365103</id><published>2010-01-08T20:38:00.005-02:00</published><updated>2010-01-08T20:58:34.709-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='apl'/><category scheme='http://www.blogger.com/atom/ns#' term='language'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Why do I love APL?</title><content type='html'>I love the strangest languages for various reasons. Some of them have immense power, but can easily produce unmaintainable messes. Some have the elegant simplicity of zen, but never attracted the people who build kitchen sinks. Some are perfect matches for certain applications, and quickly degenerate for other usages.&lt;br /&gt;&lt;br /&gt;In Scala I have found for the first time a positive combination of these attributes. Immense power, kitchen sinks, check. Simplicity? Perhaps not, but more so than the more popular alternatives. Some code has definitely a zen-like quality to it. And, yet, it is of general use, and has good enough resilience against unmaintainable messes. Not perfect, but better than anything else I know of, for now.&lt;br /&gt;&lt;br /&gt;That doesn't mean I do not appreciate other languages. There is much to learn and admire in many, many languages, and I would not mind using quite a few of them if chance favors it.&lt;br /&gt;&lt;br /&gt;So I'll leave you with the answer that came to my mind as I explained to a bewildered person why I loved APL -- a language I could spend a whole afternoon producing half a line of code:&lt;br /&gt;&lt;br /&gt;&lt;blockquote&gt;&lt;p&gt;There's joy to be found in writing code which is solely about what you want, and not about how to get there. Of expressing the fulness of your intent as a single expression. It's like the ultimate perfect katana cut.&lt;br /&gt;&lt;br /&gt;Of course, in a real fight I'd rather have a gun.&lt;/p&gt;&lt;/blockquote&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-8031554644693365103?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/8031554644693365103/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2010/01/why-do-i-love-apl.html#comment-form' title='7 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8031554644693365103'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8031554644693365103'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2010/01/why-do-i-love-apl.html' title='Why do I love APL?'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>7</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-8684512031674872733</id><published>2009-10-30T22:27:00.006-02:00</published><updated>2009-10-31T03:18:21.162-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='beginner'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>99 Beers!</title><content type='html'>I was perusing Lau Jensen's excellent &lt;a href="http://blog.bestinclass.dk/"&gt;Best In Class&lt;/a&gt; blog. Now, Lau Jensen is a Clojure-person, and that's one of the best languages out there in my opinion. So, when he compares it to other languages, that's never a nice experience to those being compared.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Personally, I think OO and infix methods (dot-style or operator notation) are essential for a well-rounded, popular language, which makes something of an uncrossable chasm between Clojure and me for "serious" stuff.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;At any rate, his recent &lt;a href="http://blog.bestinclass.dk/index.php/2009/10/python-vs-clojure-reloaded/"&gt;second take&lt;/a&gt; at Python got me curious about the &lt;a href="http://rosettacode.org/wiki/Main_Page"&gt;Rosetta Code&lt;/a&gt; project. First, I got curious about his discussion of the &lt;a href="http://rosettacode.org/wiki/Count_programming_examples"&gt;Counting Programming Example&lt;/a&gt; problem, and the Python and Clojure implementations shown. I took my own shot at it, going the parallel way like the Clojure version, but I'm unsatisfied with the result. Sure, it is short, but it lacks... sense of cohesion, I guess. In fact, I just changed it from what I submitted to Rosetta. Here:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;pre class="brush: scala; wrap-lines: false"&gt;import java.net.{URL, URLEncoder}&lt;br /&gt;&lt;br /&gt;val URLs = Map(&lt;br /&gt;  'allTasks -&gt; "http://www.rosettacode.org/w/api.php?action=query&amp;list=categorymembers&amp;cmtitle=Category:Programming_Tasks&amp;cmlimit=500&amp;format=xml",&lt;br /&gt;  'oneTask -&gt; "http://www.rosettacode.org/w/index.php?title=%s&amp;action=raw"&lt;br /&gt;  )&lt;br /&gt;def oneTaskURL(title: String) = URLs('oneTask) format URLEncoder.encode(title.replace(' ', '_'), "UTF-8")&lt;br /&gt;&lt;br /&gt;def getPage(url: String) = scala.io.Source.fromURL(new URL(url))(scala.io.Codec.UTF8)&lt;br /&gt;&lt;br /&gt;val pattern = "(?i)==\\{\\{header\\|".r&lt;br /&gt;def countPattern(title: String) =&lt;br /&gt;  pattern findAllIn (getPage(oneTaskURL(title)) mkString) length&lt;br /&gt;&lt;br /&gt;val allTasks = scala.xml.parsing.XhtmlParser(getPage(URLs('allTasks)))&lt;br /&gt;val counts = &lt;br /&gt;  for (task &lt;- allTasks \\ "cm" \\ "@title" map (_.text)) &lt;br /&gt;  yield actors.Futures.future((task, countPattern(task)))&lt;br /&gt;&lt;br /&gt;counts map (_.apply) map Function.tupled("%s: %d examples." format (_, _)) foreach println&lt;br /&gt;println("\nTotal: %d examples." format (counts map (_.apply._2) sum))&lt;br /&gt;&lt;/pre&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I won't bother explaining it, because I think it is self-explanatory, if a bit arcane. Scala's partial XPath support is put to good use, and future just works here. In case you aren't familiar with Future, it just detaches a thread to handle some computation you passed, and then, when you call "apply", it joins that thread and get the result. Sort of. If anyone wants to take a go at making this better, I'd like to see the results.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;At any rate, while perusing the Rosetta site, I noticed that &lt;a href="http://rosettacode.org/wiki/99_Bottles_of_Beer"&gt;99 Bottles of Beer&lt;/a&gt; problem allowed for creativity in reaching a solution. Most examples went for conciseness. My own concise Scala looks like this:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;pre class="brush: scala"&gt;99 to 1 by -1 foreach {n =&gt;&lt;br /&gt;  println("""|%d bottles of beer on the wall&lt;br /&gt;             |%d bottles of beer&lt;br /&gt;             |Take one down, pass it around&lt;br /&gt;             |%d bottles of beer on the wall\n""".stripMargin format (n, n, n -1))}&lt;br /&gt;&lt;/pre&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;However, as I thought about the problem and how to make it interesting, I decided to model it with Actors. Sure, it is an absolute overkill for this problem, but I think the modelling itself shows off Actors pretty nice.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Here it is:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;pre class="brush: scala"&gt;object Song {&lt;br /&gt;  import scala.actors._&lt;br /&gt;  import scala.actors.Actor._&lt;br /&gt;  &lt;br /&gt;  abstract class Beverage { def name = this.toString.toLowerCase }&lt;br /&gt;  case object Beer extends Beverage&lt;br /&gt;  &lt;br /&gt;  object Wall {&lt;br /&gt;    private var contents: List[Beverage] = Nil&lt;br /&gt;    &lt;br /&gt;    def count(what: Beverage) = contents count (_ == what)&lt;br /&gt;    def isEmpty = contents isEmpty&lt;br /&gt;    def stock(n: Int, what: Beverage) = contents :::= List.fill(n)(what)&lt;br /&gt;    def get(what: Beverage) {&lt;br /&gt;      def takeOneFrom(contents: List[Beverage]): List[Beverage] = contents match {&lt;br /&gt;        case `what` :: rest =&gt; rest&lt;br /&gt;        case other :: rest =&gt; other :: takeOneFrom(rest)&lt;br /&gt;        case Nil =&gt; println("Sorry, we are out of "+what.name); Nil&lt;br /&gt;      }&lt;br /&gt;      contents = takeOneFrom(contents)&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  sealed abstract class Messages&lt;br /&gt;  case class SingSong(what: Beverage) extends Messages&lt;br /&gt;  case class HowManyMore(what: Beverage) extends Messages&lt;br /&gt;  case class HowManyNow(what: Beverage) extends Messages&lt;br /&gt;  case class ThereAreStill(n: Int, what: Beverage) extends Messages&lt;br /&gt;  case class ThereAreNow(n: Int, what: Beverage) extends Messages&lt;br /&gt;  case class Gimme(what: Beverage) extends Messages&lt;br /&gt;  case class HereIs(what: Beverage) extends Messages&lt;br /&gt;  case object ClosingTime extends Messages&lt;br /&gt;  &lt;br /&gt;  def plural(count: Int, noun: String, nouns: String) = if (count == 1) noun else nouns&lt;br /&gt;  def countIt(n: Int, what: Beverage) = "%d %s of %s" format (n, plural(n, "bottle", "bottles"), what.name) &lt;br /&gt;  &lt;br /&gt;  object Waitress extends Actor {&lt;br /&gt;    def tellThem(what: String) = println("%s on the wall" format what)&lt;br /&gt;    def act = loop {&lt;br /&gt;      react {&lt;br /&gt;        case HowManyMore(it) =&gt;&lt;br /&gt;          val total = Wall count it&lt;br /&gt;          tellThem(countIt(total, it))&lt;br /&gt;          reply (ThereAreStill(total, it))&lt;br /&gt;        case Gimme(it) =&gt;&lt;br /&gt;          print("Take one down, ")&lt;br /&gt;          Wall get it&lt;br /&gt;          reply (HereIs(it))&lt;br /&gt;        case HowManyNow(it) =&gt;&lt;br /&gt;          val total = Wall count it&lt;br /&gt;          tellThem(countIt(total, it))&lt;br /&gt;          if (Wall isEmpty) {&lt;br /&gt;              reply (ClosingTime) // You don't have to go home, but you can't stay here&lt;br /&gt;              exit&lt;br /&gt;          } else&lt;br /&gt;          reply (ThereAreNow(total, it))&lt;br /&gt;        case _ =&gt;&lt;br /&gt;          println("You wish, honey!")&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;  &lt;br /&gt;  object Patrons extends Actor {&lt;br /&gt;    def act = loop {&lt;br /&gt;      react {&lt;br /&gt;        case SingSong(what: Beverage) =&gt;&lt;br /&gt;          Waitress ! HowManyMore(what)&lt;br /&gt;        case ThereAreStill(n, it) =&gt;&lt;br /&gt;          println(countIt(n, it))&lt;br /&gt;          Waitress ! Gimme(it)&lt;br /&gt;        case HereIs(it) =&gt;&lt;br /&gt;          println("pass it around")&lt;br /&gt;          Waitress ! HowManyNow(it)&lt;br /&gt;        case ThereAreNow(n, it) =&gt;&lt;br /&gt;          println()&lt;br /&gt;          Waitress ! HowManyMore(it)&lt;br /&gt;        case ClosingTime =&gt;&lt;br /&gt;          exit&lt;br /&gt;        case _ =&gt;&lt;br /&gt;          println("Say what???")&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;  &lt;br /&gt;  def Sing99Beers = {&lt;br /&gt;    Wall stock (99, Beer)&lt;br /&gt;    Waitress.start&lt;br /&gt;    Patrons.start&lt;br /&gt;    &lt;br /&gt;    Patrons ! SingSong(Beer)&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now, this code has a structure to it. To begin with, there are two concerns. First, there is the "wall", where the beverages are kept, and the beverages themselves. The beverages are modeled as case objects derived from a sealed class, which is an alternative to enumerations, as I have discussed in my &lt;a href="http://dcsobral.blogspot.com/search/label/matrix"&gt;Matrix&lt;/a&gt; series.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I suppose the wall ought to be synchronized, but I'm working with an assumption here. Only one agent can get things from the wall, and the wall can only be restocked while that agent is not working. It would be nice to have this enforced by the compiler, and a paper from the EPFL guys gives me hope of being able to in the future.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The second concern is the interaction between the patrons and the waitress. Again, it is further divided into two: the messages they exchange between themselves, and the actors themselves and their behavior.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Defining the messages as a subclass from an abstract class doesn't really give me anything. The Actors in the standard library are untyped, so they can receive anything as message. There is one typed Actor library for Scala, though, which is a model much more to my liking. If used, I'd not have to provide for handling of unknown messages.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The song gets sang as the patrons ask how many beers there are, the waitress answers, the patrons order one beer, get it, and then ask again how many beers there are. No actor ever waits for the answer. Instead, they finish their present reaction, and wait for another message -- which might be the answer they were waiting for, or not. What the actor do is solely defined by what message they received.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;To get the song started, the wall is first stocked, patrons and waitress started, and, then, the patrons are asked to begin the song. I'm pretty sure bar owners everywhere hope it would be this easy to get people drinking until the stock is sold-out. :-)&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I hope you enjoyed this post half as much as I enjoyed writing that code! If you are feeling the need to write some code &lt;i&gt;right now&lt;/i&gt;, try modifying the program so that, when the stock of whatever is being consumed is finished, the patrons ask what else there is, and start a new song on a new beverage.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Or, better yet, why don't you find a fun problem on Rosetta Code, for which no solution exists in a language you like, and submit a solution to it? It's as easy as editting a wiki article, so go for it!&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-8684512031674872733?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/8684512031674872733/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/10/99-beers.html#comment-form' title='7 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8684512031674872733'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8684512031674872733'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/10/99-beers.html' title='99 Beers!'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>7</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-2192102288018463403</id><published>2009-10-28T12:00:00.008-02:00</published><updated>2010-12-30T09:03:52.689-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='beginner'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Strict Ranges?</title><content type='html'>&lt;b&gt;Note:&lt;/b&gt; This article was created before Scala 2.8.0 was out, and is mostly related to a problem that is no longer present as of that version. The code in here is supposed to be run on Scala 2.7.x unless otherwise noted, and the output of Scala 2.8.0 usually refers to some work-in-progress version of it, not the final version.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;A common mistake newcomers to Scala usually make is to treat Scala ranges as strict. It's easy to see why they make such mistake, because the very expression "strict", though relatively easy to find in the Scala API documentation, is unfamiliar to them.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, before getting into the problem, I'll make a brief detour. In functional languages, there is a concept of "strict functions" and "non-strict functions". Informally, a "strict function" is one which always evaluates its argument. For programmers from a non-functional background, that's most of the functions they ever saw, but not all. For instance, the trinary operator, "test ? f1 : f2", does not evaluate all its arguments, f1 and f2, even though it always evaluate at least one of them.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now, to see where that can lead to trouble, let's first see an example of non-strictness in action, with Scala 2.7:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;pre class="brush: scala"&gt;scala&gt; object X {&lt;br /&gt;| val x = -10 to 10 map (2 / _)&lt;br /&gt;| }&lt;br /&gt;defined module X&lt;br /&gt;&lt;br /&gt;scala&gt; object Y {&lt;br /&gt;| val y = List.range(-10, 10) map (2 / _)&lt;br /&gt;| }&lt;br /&gt;defined module Y&lt;br /&gt;&lt;br /&gt;scala&gt; Y.y(0)&lt;br /&gt;java.lang.ArithmeticException: / by zero&lt;br /&gt;at Y$$anonfun$1.apply(&amp;lt;console&gt;:5)&lt;br /&gt;at Y$$anonfun$1.apply(&amp;lt;console&gt;:5)&lt;br /&gt;at scala.List.map(List.scala:812)&lt;br /&gt;at Y$.&amp;lt;init&gt;(&amp;lt;console&gt;:5)&lt;br /&gt;at Y$.&amp;lt;clinit&gt;(&amp;lt;console&gt;)&lt;br /&gt;at .&amp;lt;init&gt;(&amp;lt;console&gt;:6)&lt;br /&gt;at .&amp;lt;clinit&gt;(&amp;lt;console&gt;)&lt;br /&gt;at RequestResult$.&amp;lt;init&gt;(&amp;lt;console&gt;:3)&lt;br /&gt;at RequestResult$.&amp;lt;clinit&gt;(&amp;lt;console&gt;)&lt;br /&gt;at RequestResult$result(&amp;lt;console&gt;)&lt;br /&gt;at sun.reflect.Nativ...&lt;br /&gt;scala&gt; X.x(0)&lt;br /&gt;res2: Int = 0&lt;/pre&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;We see an error happens when the map on the list is applied, but not when the map on the range is applied. That's because the function "map" for Range (the result of "x to y" or "x until y" expressions) is non-strict. I can get the value for any part of that Range, except the eleventh element, without throwing an exception.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;But let say we have a function expensiveComputation, which takes quite a while to process. What happens, then, if I do this:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;pre class="brush: scala"&gt;scala&gt; import scala.actors.Futures._&lt;br /&gt;import scala.actors.Futures._&lt;br /&gt;&lt;br /&gt;scala&gt; val m = 1 to 1000 map (i =&gt; future(expensiveComputation(i)))&lt;br /&gt;m: RandomAccessSeq.Projection[scala.actors.Future[Int]] = RangeM(&amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;,&lt;br /&gt;&amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;fu&lt;br /&gt;nction&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;functi&lt;br /&gt;on&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;, &amp;lt;function&gt;...&lt;/pre&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;If you haven't seen it before, the "future" function uses threads to compute the function you passed to it. Your program can go on to do other stuff, while all that work is being done concurrently.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Except, of course, that's not what's happening. No computation is being done, because Range's non-strict map hasn't evaluated its arguments.  In fact, &lt;i&gt;each time&lt;/i&gt; I call "apply" to get the result of the computation, the function I passed to map (the future) will be computed again! For example:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;pre class="brush: scala"&gt;scala&gt; def expensiveComputation(n: Int) = {&lt;br /&gt;|   println("Starting expensive computation")&lt;br /&gt;|   val x = n * 2&lt;br /&gt;|   println("Finished expensive computation")&lt;br /&gt;|   x&lt;br /&gt;| }&lt;br /&gt;expensiveComputation: (Int)Int&lt;br /&gt;&lt;br /&gt;scala&gt; val m = 1 to 10 map (i =&gt; future(expensiveComputation(i)))&lt;br /&gt;(output from "m.toString" skipped)&lt;br /&gt;&lt;br /&gt;scala&gt; m(0).apply&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;res12: Int = 2&lt;br /&gt;&lt;br /&gt;scala&gt; m(0).apply&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;res13: Int = 2&lt;/pre&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;To see where that can be a problem to beginners, take a look at the code in &lt;a href="http://stackoverflow.com/questions/1313979/thread-join-not-behaving-as-i-expected-in-scala"&gt;this question&lt;/a&gt; at &lt;a href="http://stackoverflow.com/"&gt;Stack Overflow&lt;/a&gt;:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;pre class="brush: scala"&gt;def ttest() = {&lt;br /&gt;val threads =&lt;br /&gt;for (i &amp;lt;- 1 to 5)&lt;br /&gt;yield new Thread() {&lt;br /&gt;override def run() {&lt;br /&gt;println("going to sleep")&lt;br /&gt;Thread.sleep(1000)&lt;br /&gt;println("awake now")&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;threads.foreach(t =&gt; t.start())&lt;br /&gt;threads.foreach(t =&gt; t.join())&lt;br /&gt;println("all done")&lt;br /&gt;}&lt;/pre&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Can you imagine what happens?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Well, gladly, Scala 2.8 should have a strict Range, so newcomers will be spared the trouble and lost debugging time. Here's what this will look like with Scala 2.8:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;pre class="brush: scala"&gt;scala&gt; val m = 1 to 10 map (i =&gt; future(expensiveComputation(i)))&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;m: scala.collection.immutable.Vector[scala.actors.Future[Int]] = NewVectorImpl(&amp;lt;function0&gt;, &amp;lt;function0&gt;, &amp;lt;function0&gt;, &amp;lt;f&lt;br /&gt;unction0&gt;, &amp;lt;function0&gt;, &amp;lt;function0&gt;, &amp;lt;function0&gt;, &amp;lt;function0&gt;, &amp;lt;function0&gt;, &amp;lt;function0&gt;)&lt;br /&gt;Finished expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;&lt;br /&gt;scala&gt; Finished expensive computation&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;scala&gt; m(0).apply&lt;br /&gt;res11: Int = 2&lt;br /&gt;&lt;br /&gt;scala&gt; m(0).apply&lt;br /&gt;res12: Int = 2&lt;/pre&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Also, if you try out the first code snippet on Scala 2.8, "x.x(0)" will also throw an exception. Now, if we want the previous behavior, we can just call the "view" method. It will work not only on Range, but on pretty much all standard collections, as it is defined on the class IterableLike.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;pre class="brush: scala"&gt;scala&gt; val m = (1 to 10 view) map (i =&gt; future(expensiveComputation(i)))&lt;br /&gt;m: scala.collection.SeqView[scala.actors.Future[Int],Seq[_]] = SeqViewM(...)&lt;br /&gt;&lt;br /&gt;scala&gt; m.toList&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;res5: List[scala.actors.Future[Int]] = List(&lt;function0&gt;, &lt;function0&gt;, &lt;function0&gt;, &lt;function0&gt;, &lt;function0&gt;, &lt;function0&gt;&lt;br /&gt;, &lt;function0&gt;, &lt;function0&gt;, &lt;function0&gt;, &lt;function0&gt;)&lt;br /&gt;Finished expensive computation&lt;br /&gt;&lt;br /&gt;scala&gt; m(0).apply&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;res6: Int = 2&lt;br /&gt;&lt;br /&gt;scala&gt; m(0).apply&lt;br /&gt;Starting expensive computation&lt;br /&gt;Finished expensive computation&lt;br /&gt;res7: Int = 2&lt;/pre&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;And, for the first example:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;pre class="brush: scala"&gt;scala&gt; object X {&lt;br /&gt;| val x = (-10 to 10 view) map (2 / _)&lt;br /&gt;| }&lt;br /&gt;defined module X&lt;br /&gt;&lt;br /&gt;scala&gt; object Y {&lt;br /&gt;| val y = List.range(-10, 10).view map (2 / _)&lt;br /&gt;| }&lt;br /&gt;defined module Y&lt;br /&gt;&lt;br /&gt;scala&gt; Y.y(0)&lt;br /&gt;res0: Int = 0&lt;br /&gt;&lt;br /&gt;scala&gt; X.x(0)&lt;br /&gt;res1: Int = 0&lt;/pre&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;And, speaking of Scala 2.8 changes, there is one that is also likely to reduce confusion among newcomers, and is related to what we spoke of. It's related to how guards on for-comprehensions work. For instance, take a look at this code:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;pre class="brush: scala"&gt;scala&gt; def find(n: Int, l: List[Int]) = {&lt;br /&gt;| var found = false&lt;br /&gt;| for (el &amp;lt;- l; if !found) found = el == n&lt;br /&gt;| found&lt;br /&gt;| }&lt;br /&gt;find: (Int,List[Int])Boolean&lt;br /&gt;&lt;br /&gt;scala&gt; find(5, List.range(1, 10))&lt;br /&gt;res14: Boolean = false&lt;/pre&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This code doesn't work as expected because of how for-comprehensions are translated:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;pre class="brush:scala"&gt;l.filter(el =&gt; !found).foreach(el =&gt; found = el == n)&lt;/pre&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Since "filter" for List is a strict method, this just doesn't work, as "filter" evaluates before "foreach". However, Range's "filter" on Scala 2.7 is non-strict. Does it work? Yes:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;pre class="brush: scala"&gt;scala&gt; def findR(n: Int, l: Range) = {&lt;br /&gt;| var found = false&lt;br /&gt;| for (el &amp;lt;- l; if !found) found = el == n&lt;br /&gt;| found&lt;br /&gt;| }&lt;br /&gt;findR: (Int,Range)Boolean&lt;br /&gt;&lt;br /&gt;scala&gt; findR(5, 1 to 10)&lt;br /&gt;res17: Boolean = true&lt;/pre&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;But, back to the first example, as of Scala 2.8 the for-comprehension code will translate like this:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;pre class="brush:scala"&gt;l.withFilter(el =&gt; !found).foreach(el =&gt; found = el == n)&lt;/pre&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This new function, "withFilter", will be non-strict for standard Scala collections. There's no way, however, to ensure that third-party collections will preserve the non-strictness. Hopefully, people will act in a sensible manner! :-) At any rate, the "find" function, as written, will work on Scala 2.8.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I hope this helps people working with Scala 2.7, and hope even more for Scala 2.8 to arrive soon! As a parting thought, though, I'd like to briefly speak of "&lt;-", seen in for-comprehensions. I have seen people calling it many things. Martin Odersky's (et al) Programming in Scala book, however, calls it "in". So "for (el &lt;- l)" ought to read "for el in l". So, if you weren't sure what to call it, now you know! Happy coding!&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-2192102288018463403?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/2192102288018463403/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/10/strict-ranges.html#comment-form' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/2192102288018463403'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/2192102288018463403'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/10/strict-ranges.html' title='Strict Ranges?'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-2455470424700657835</id><published>2009-09-29T23:26:00.003-03:00</published><updated>2009-09-30T19:00:40.250-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='continuations'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Scala's Delimited Continuations -- A Use Case</title><content type='html'>When I &lt;a href="http://dcsobral.blogspot.com/2009/07/delimited-continuations-explained-in.html"&gt;first talked&lt;/a&gt; about the upcoming Scala 2.8 Delimited Continuations, I did not go into what uses I foresaw for them, mostly because I was pretty sure people would find uses I could never have imagined for it.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Well, people did find uses I could never have imagined, it turns out! If Scala and Distributed Computing are your things -- hell, if even one of them is your thing! -- do go check &lt;a href="http://vimeo.com/6614042"&gt;Swarm&lt;/a&gt; out.&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-2455470424700657835?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/2455470424700657835/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/09/scalas-delimited-continuations-use-case.html#comment-form' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/2455470424700657835'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/2455470424700657835'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/09/scalas-delimited-continuations-use-case.html' title='Scala&apos;s Delimited Continuations -- A Use Case'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-8096499323399441363</id><published>2009-09-17T22:46:00.002-03:00</published><updated>2009-09-17T23:03:48.925-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='agile'/><category scheme='http://www.blogger.com/atom/ns#' term='rewritting'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Is rewritting really bad?</title><content type='html'>Paul Chiusano tell us his &lt;a href="http://pchiusano.blogspot.com/2009/08/scala-success-story-commercial-usage-of.html"&gt;Scala success story&lt;/a&gt;, and while I find it interesting, there's something that attracts my attention in it. He says:&lt;div&gt;&lt;span class="Apple-style-span" style="color: rgb(51, 51, 51); font-size: 13px; line-height: 20px; "&gt;&lt;blockquote&gt;Finally, I'd like to scrutinize the folk wisdom that rewrites are generally a bad idea.&lt;/blockquote&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;blockquote&gt;&lt;/blockquote&gt;That got me thinking a bit. That wisdom predates some developments which only became widespread practices recently. In particular, BDD and Continuous Integration.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;It occurs to me that if I decide to rewrite something from scratch, I'll have a large set of tests in the form of BDD (which tests for Behavior, so a lot of it should still apply), plus the tests for all bugs that were caught and fixed, for which you them add tests to help with CI.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Furthermore, because you are doing BDD and CI, and possibly TDD for low level stuff, you won't get far with the same errors in case you re-introduce them.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;That's something to think about... maybe the old wisdom requires some revisiting.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;At any rate, I'd like to point out that this particular piece of wisdom might have become widespread because of &lt;a href="http://www.joelonsoftware.com/articles/fog0000000069.html"&gt;this article&lt;/a&gt; by Joel Spolsky. I'll quote one part of it, though:&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span" style="line-height: 20px; "&gt;&lt;blockquote&gt;These problems can be solved, one at a time, by carefully moving code, refactoring, changing interfaces. They can be done by one programmer working carefully and checking in his changes all at once, so that nobody else is disrupted. Even fairly major architectural changes can be done without &lt;i&gt;throwing away the code&lt;/i&gt;.&lt;/blockquote&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;Well, that's precisely what Paul Chiusano did! So, on the other hand, perhaps is too soon to dispose of that wisdom...&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-8096499323399441363?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/8096499323399441363/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/09/is-rewritting-really-bad.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8096499323399441363'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8096499323399441363'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/09/is-rewritting-really-bad.html' title='Is rewritting really bad?'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-8312238252293106409</id><published>2009-09-09T21:29:00.004-03:00</published><updated>2009-09-09T22:07:14.594-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Type Safe Builder Pattern</title><content type='html'>I was reading these days an &lt;a href="http://jim-mcbeath.blogspot.com/2009/09/type-safe-builder-in-scala-using-church.html"&gt;interesting article&lt;/a&gt; by &lt;a href="http://jim-mcbeath.blogspot.com/"&gt;Jim McBeath&lt;/a&gt; about type safe builder patterns. The interesting part was the use of &lt;a href="http://en.wikipedia.org/wiki/Church_encoding"&gt;Church encoding&lt;/a&gt; to be able to control the ordinality of certain types, but as I went to the &lt;a href="http://blog.rafaelferreira.net/2008/07/type-safe-builder-pattern-in-scala.html"&gt;original article&lt;/a&gt; by &lt;a href="http://blog.rafaelferreira.net/"&gt;Rafael de F. Ferreira&lt;/a&gt;, I found the silliest criticism, which I quote below:&lt;div&gt;&lt;span class="Apple-style-span"  style="font-family:Verdana;"&gt;&lt;span class="Apple-style-span" style=" line-height: 16px;"&gt;&lt;i&gt;&lt;span class="Apple-style-span"  style="font-family:Georgia;"&gt;&lt;span class="Apple-style-span" style=" font-style: normal; line-height: normal;"&gt;&lt;span class="Apple-style-span"  style="font-size:medium;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/i&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;&lt;i&gt;My but it's sad that Java/Scala has to resort to a design pattern for this (if I'm understanding the post correctly).&lt;/i&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;&lt;br /&gt;&lt;/i&gt;&lt;/div&gt;&lt;div&gt;&lt;i&gt;In Python, we have keyword arguments and default argument values, which allows for very rich parameter declarations.&lt;/i&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Well, first of all, a builder pattern is targetted at complex objects. Imagine, for instance, a maze with multiple rooms and passages, where the creation process might entail adding hundred of such components. Not exactly the sort of thing you want to pass as a single parameter list, I'd imagine. In fact, it might not even be possible to do it, because you might not have all information needed in the same place and/or time.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;But, most importantly, "keyword arguments" do not enforce type safety. So even if it were an alternative to any problem requiring the Builder pattern, it would fail at the basic premise of the article, which is providing type safety.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, I decided to show something you can't do with keyword arguments, which, by the way, are called "named parameters" in Scala 2.8, which is mutual exclusion. I'm adapting this example from &lt;a href="http://gist.github.com/182249"&gt;here&lt;/a&gt;, which was written in reply to a &lt;a href="http://jim-mcbeath.blogspot.com/2009/09/type-safe-builder-in-scala-part-2.html"&gt;follow up&lt;/a&gt; by Jim on his original article.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;For this example, I assume a "Car" builder, where one has to make a choice about number of doors and brand, and may also choose to get a convertible, but the convertible is incompatible with cars with five doors. This code is nowhere as clear as Jim's, but gets the job done faster, so I could get on with my life. :-)&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, I hope you like it. And if you can clean it up, or come up with more likely scenarios, please share it.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;// This code is based on an idea of Rafael de F. Ferreira and was implemented as a response to&lt;br /&gt;// Jim McBeath's blog post http://jim-mcbeath.blogspot.com/2009/09/type-safe-builder-in-scala-part-2.html&lt;br /&gt;// Everyone is free to use, modify, republish, sell or give away this work without prior consent from anybody.&lt;br /&gt;&lt;br /&gt;object Scotch {&lt;br /&gt;sealed abstract class Preparation&lt;br /&gt;case object Neat extends Preparation&lt;br /&gt;case object OnTheRocks extends Preparation&lt;br /&gt;case object WithWater extends Preparation&lt;br /&gt;&lt;br /&gt;case class OrderOfScotch private[Scotch](val brand:String, val mode:Preparation, val isDouble:Boolean)&lt;br /&gt;&lt;br /&gt;trait Option[+X]&lt;br /&gt;case class Some[+X](x:X) extends Option[X]{&lt;br /&gt;  def get:X = x&lt;br /&gt;}&lt;br /&gt;trait None extends Option[Nothing] // this differs in the original implementation&lt;br /&gt;case object None extends None&lt;br /&gt;&lt;br /&gt;case class Builder[HAS_BRAND&amp;lt;:Option[String],HAS_MODE&amp;lt;:Option[Preparation],HAS_DOUBLE&amp;lt;:Option[Boolean]] private[Scotch]&lt;br /&gt;             (brand:HAS_BRAND&lt;br /&gt;             ,mode:HAS_MODE&lt;br /&gt;             ,isDouble:HAS_DOUBLE&lt;br /&gt;             ) {&lt;br /&gt;  def ~[X](f:Builder[HAS_BRAND,HAS_MODE,HAS_DOUBLE] =&gt; X):X = f(this)&lt;br /&gt;}&lt;br /&gt;           &lt;br /&gt;def withBrand[M&amp;lt;:Option[Preparation],D&amp;lt;:Option[Boolean]](brand:String)(b:Builder[None,M,D]):Builder[Some[String],M,D] =&lt;br /&gt;  Builder(Some(brand),b.mode,b.isDouble)&lt;br /&gt;def withMode[B&amp;lt;:Option[String],D&amp;lt;:Option[Boolean]](mode:Preparation)(b:Builder[B,None,D]):Builder[B,Some[Preparation],D] =&lt;br /&gt;  Builder(b.brand,Some(mode),b.isDouble)&lt;br /&gt;def isDouble[B&amp;lt;:Option[String],M&amp;lt;:Option[Preparation]](isDouble:Boolean)(b:Builder[B,M,None]):Builder[B,M,Some[Boolean]] =&lt;br /&gt;  Builder(b.brand,b.mode,Some(isDouble))&lt;br /&gt;&lt;br /&gt;def build(b:Builder[Some[String],Some[Preparation],Some[Boolean]]):OrderOfScotch =&lt;br /&gt;  OrderOfScotch(b.brand.get,b.mode.get,b.isDouble.get)&lt;br /&gt;&lt;br /&gt;def builder:Builder[None,None,None] = Builder(None,None,None)&lt;br /&gt;&lt;br /&gt;def test {&lt;br /&gt;  val x:OrderOfScotch = builder ~ isDouble(true) ~ withMode(Neat) ~ withBrand("Blubber") ~ build&lt;br /&gt;  // builder ~ isDouble(true) ~ withMode(Neat) ~ build // fails&lt;br /&gt;  // builder ~ isDouble(true) ~ withMode(Neat) ~ withBrand("Blubber") ~ withBrand("Blubber") ~ build // fails&lt;br /&gt;  x&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-8312238252293106409?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/8312238252293106409/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/09/type-safe-builder-pattern.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8312238252293106409'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8312238252293106409'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/09/type-safe-builder-pattern.html' title='Type Safe Builder Pattern'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-7860189663764745616</id><published>2009-09-08T22:21:00.003-03:00</published><updated>2009-09-08T22:35:14.110-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='puzzle'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>A Number Puzzle</title><content type='html'>My friend came up with a new puzzle. Given a 3x3 matrix, fill it with the numbers 1 through 9, without repetition, in such a way that adding the three digits from any line, column or diagonal will yield exactly the same result.&lt;br /&gt; &lt;br /&gt;This time I went for conciseness. Instead of laying out a 3x3 array -- or what have you -- I'll take a list of 9 elements, and assume the elements are laid out left to right, then top to down, so that the third element of the second line is the sixth element of the list, for example. Now, before I try to solve it, I have to devise a way to test the conditions. First, let's create a list of list of indices for each line, column of diagonal possible. This can be done programmatically, of course, like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt; &lt;br /&gt;val cols = List.range(0,3)&lt;br /&gt;val lines = cols map (_ * 3)&lt;br /&gt;val allLines = lines map (l =&gt; cols map (l + _))&lt;br /&gt;val allCols = cols map (c =&gt; lines map (c + _))&lt;br /&gt;val diagLR = lines zip cols map Function.tupled(_+_)&lt;br /&gt;val diagRL = lines zip cols.reverse map Function.tupled(_+_)&lt;br /&gt;val indices = diagLR :: diagRL :: allLines ::: allCols&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt; &lt;br /&gt;I decided just to enter it by hand, though:&lt;br /&gt; &lt;br /&gt;&lt;pre class="brush:scala"&gt; &lt;br /&gt;val indices = List(List(0,1,2), List(3,4,5), List(6,7,8), List(0,3,6), List(1,4,7), List(2,5,8), List(0,4,8), List(2,4,6))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt; &lt;br /&gt;Now, I want to test this. Suppose I have a list of numbers representing the solution. I can replace the indices by the corresponding number like this:&lt;br /&gt; &lt;br /&gt;&lt;pre class="brush:scala"&gt; &lt;br /&gt;indices map (_ map (solution(_)))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt; &lt;br /&gt;from which is quite easy to compute how much each line, column and diagonal adds to:&lt;br /&gt; &lt;br /&gt;&lt;pre class="brush:scala"&gt; &lt;br /&gt;indices map (_ map (solution(_)) sum)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt; &lt;br /&gt;One way, then, to check if all numbers are equal is to simply compare them:&lt;br /&gt; &lt;br /&gt;&lt;pre class="brush:scala"&gt; &lt;br /&gt;indices map (_ map (solution(_)) sum) match { case head :: tail =&gt; tail forall (_ == head) }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt; &lt;br /&gt;Not concise enough for me, though. I prefer this:&lt;br /&gt; &lt;br /&gt;&lt;pre class="brush:scala"&gt; &lt;br /&gt;(indices map (_ map (solution(_)) sum) removeDuplicates).size == 1&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt; &lt;br /&gt;Our test function, then, is:&lt;br /&gt; &lt;br /&gt;&lt;pre class="brush:scala"&gt; &lt;br /&gt;def test(solution: List[Int]) = (indices map (_ map (solution(_)) sum) removeDuplicates).size == 1&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt; &lt;br /&gt;Now, how to compute the solutions? We can do it recursively with lists, recursions, filters, etc. Too much work. Let's just enumerate the possible solutions. The first element can be represented by the index over a nine-elements list of a "seed" solution. The second element can be represented by an index over the eight-element list of remaining elements, and so on. We can disambiguate the first index from the second by multiplying the second by 9, and add both. We can repeat this over and over for every other element in the list. So, to go from a number representing the solution, plus a seed list, to the solution, we can write this function:&lt;br /&gt; &lt;br /&gt;&lt;pre class="brush:scala"&gt; &lt;br /&gt;def numToIndices(n: Int, l: List[Int]): List[Int] =&lt;br /&gt;  if (l.isEmpty) Nil else l(n % l.size) :: numToIndices(n / l.size, l filter (_ != l(n % l.size)))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt; &lt;br /&gt;Now, given this representation of the solutions of this problem, it should be clear that the number of solutions is the factorial of 9, so there are solutions from 0 to 9! - 1. So, let's create a seed, and, non-strictly (to avoid out of memory errors), generate our possible solutions:&lt;br /&gt; &lt;br /&gt;&lt;pre class="brush:scala"&gt; &lt;br /&gt;val seed = 1 to 9 toList&lt;br /&gt;val possibleSolutions = Stream.range(0, seed reduceLeft (_*_)) map (numToIndices(_, seed))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt; &lt;br /&gt;Keeping the head of a stream is not a good idea, though. We need to filter for the actual solutions before assigning it to any val. Which, of course, we'll give you the final solutions:&lt;br /&gt; &lt;br /&gt;&lt;pre class="brush:scala"&gt; &lt;br /&gt;val solutions = (0 until seed.reduceLeft(_*_)).toStream map (numToIndices(_, seed)) filter (test(_)) toList&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt; &lt;br /&gt;Not particularly efficient, but the line count is good:&lt;br /&gt; &lt;br /&gt;&lt;pre class="brush:scala"&gt; &lt;br /&gt;val indices = List(List(0,1,2), List(3,4,5), List(6,7,8), List(0,3,6), List(1,4,7), List(2,5,8), List(0,4,8), List(2,4,6))&lt;br /&gt;def test(solution: List[Int]) = (indices map (_ map (solution(_)) sum) removeDuplicates).size == 1&lt;br /&gt;def numToIndices(n: Int, l: List[Int]): List[Int] =&lt;br /&gt;  if (l.isEmpty) Nil else l(n % l.size) :: numToIndices(n / l.size, l filter (_ != l(n % l.size)))&lt;br /&gt;val seed = 1 to 9 toList&lt;br /&gt;val solutions = (0 until seed.reduceLeft(_*_)).toStream map (numToIndices(_, seed)) filter (test(_)) toList&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt; &lt;br /&gt;Which we can then print with:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt; &lt;br /&gt;println(solutions map (_.iterator grouped 3 map (_ mkString) mkString "\n") mkString "\n")&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-7860189663764745616?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/7860189663764745616/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/09/number-puzzle.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/7860189663764745616'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/7860189663764745616'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/09/number-puzzle.html' title='A Number Puzzle'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-6735671050178839363</id><published>2009-09-04T20:35:00.012-03:00</published><updated>2009-09-08T22:27:59.398-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='puzzle'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>A Puzzle</title><content type='html'>&lt;div style="text-align: left;"&gt;A couple of days ago a friend of mine was playing with a puzzle I knew of a few years ago: a maze through which one had to drive a car. Here's the setup:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_vHc2CW-BnIc/SqHI4EDVSiI/AAAAAAAAAJk/KXiU5tSFlAc/s1600-h/carpuzzle.png"&gt;&lt;img src="http://1.bp.blogspot.com/_vHc2CW-BnIc/SqHI4EDVSiI/AAAAAAAAAJk/KXiU5tSFlAc/s320/carpuzzle.png" border="0" alt="" id="BLOGGER_PHOTO_ID_5377800295543032354" style="display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 320px; height: 280px; " /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div&gt;At each intersection,  the car must take one of a limited number of allowed paths, as indicated by the arrows. The goal is to reach the exit on the other side.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;At any rate, I felt an urge to solve it programmatically -- in Scala, of course. So, later, I sat down and started coding the solution. The first step, obviously, was getting the maze into some sort of data structure. I briefly tried to find the data being used in the puzzle, but gave up on it. Instead, I'd input the maze by hand.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I had two problems to solve, then. First, I had to figure out a good data structure to represent the maze. I thought a directed graph with the intersections as vertices seemed like a good representation to me, but the matricial nature of the maze was also appealing. So I decided on a compromise: I'd store the maze as a matrix, but each element of the matrix would be a vertex, which would be represented as a set of arrows.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The second problem related to how I'd represent the maze &lt;i&gt;before&lt;/i&gt; inputting it. I decided to write it down as a big string and then parse it, but that still leaves the problem of what to write. I pondered writing each edge, but that seemed a bit error-prone. So I decided on a rather unconventional format: I'd write the directions going out from each intersection, as well as undirected edges represented by the two directions the edge connects.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;In effect, the actual vertices of my graph are not the intersections, but the streets! Each intersection is just a set of directed edges.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, having decided all that, I wrote down the data I expected to be used for the maze:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt; val graphString = """|&lt;br /&gt;                      |DR: DR, RLD: RD LD, L: DL LR, LR: DR LR, DL: DL&lt;br /&gt;                      |UR: LU RU DU LR, LRD: LR UD LU RU LD RD, UDLR: UD LR UR LD, UDLR: UD LR RD, UL: UD UL&lt;br /&gt;                      |UDR: UD RU RD, UDLR: LR LD DR RU, UD: UD UL DL, UDR: UD UR, UD: UD LD&lt;br /&gt;                      |UDR: UD RU RD, UDLR: UR UL LR RD, UR: UD LR LU RU DR, ULR: LR UR UL DR DL, UDLR: UD UL DR&lt;br /&gt;                      |UR: UR, ULR: UL UR LR, ULR: UL UR RL, ULR: UL UR RL, UL: UL&lt;br /&gt;                      |""".stripMargin&lt;br /&gt;&lt;/pre&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Ugly as hell, but it should do the job. My task, then, was to specify the data structure, and write a parser for that.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;First, directions. Not only my input is written in terms of directions, I was thinking of solving the problem by manipulating directions. So, let's create them. I don't particularly like Scala's Enumeration class, so I went with case objects:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;object DirectionSet {&lt;br /&gt; sealed abstract class Direction&lt;br /&gt; case object Up extends Direction&lt;br /&gt; case object Down extends Direction&lt;br /&gt; case object Left extends Direction&lt;br /&gt; case object Right extends Direction&lt;br /&gt; val U = Up&lt;br /&gt; val D = Down&lt;br /&gt; val L = Left&lt;br /&gt; val R = Right&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;That gives me warnings on pattern matching, and short aliases for each direction. Please note, though, that &lt;i&gt;Scala already has objects called Left and Right&lt;/i&gt;. This shouldn't present much of a problem, but, once I improved on these objects a bit, I made sure Scala knew to which objects I was referring to. Let's talk about these improvements and show them.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;As I wrote the code, I found myself needing to get the &lt;i&gt;opposite&lt;/i&gt; direction to the one I had. This was clearly a method to be added to Direction, and so I did. Another thing I did was to write a function to convert a Char into a Direction. Later, while refactoring, it was clear this function was better as a DirectionSet method, so I added it, and, while doing it, wrote a variant for Strings, though I never use it in my final code. Let's see, them, the full object:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;object DirectionSet {&lt;br /&gt; sealed abstract class Direction {&lt;br /&gt;   def opposite: Direction&lt;br /&gt; }&lt;br /&gt; case object Up extends Direction { override def opposite = DirectionSet.Down }&lt;br /&gt; case object Down extends Direction { override def opposite = DirectionSet.Up }&lt;br /&gt; case object Left extends Direction { override def opposite = DirectionSet.Right }&lt;br /&gt; case object Right extends Direction { override def opposite = DirectionSet.Left }&lt;br /&gt; val U = Up&lt;br /&gt; val D = Down&lt;br /&gt; val L = Left&lt;br /&gt; val R = Right&lt;br /&gt; def apply(s: Char): Direction = s.toLowerCase match {&lt;br /&gt;   case 'u' =&gt; Up&lt;br /&gt;   case 'd' =&gt; Down&lt;br /&gt;   case 'l' =&gt; Left&lt;br /&gt;   case 'r' =&gt; Right&lt;br /&gt;   case _ =&gt; throw new IllegalArgumentException&lt;br /&gt; }&lt;br /&gt; def apply(s: String): Direction = s.toLowerCase match {&lt;br /&gt;   case "up" =&gt; Up&lt;br /&gt;   case "down" =&gt; Down&lt;br /&gt;   case "left" =&gt; Left&lt;br /&gt;   case "right" =&gt; Right&lt;br /&gt;   case _ =&gt; throw new IllegalArgumentException&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;And that's that. So, let's proceed. Our graph is composed of intersections, each of which is composed of the arrows present at that intersection. The next step, then, is defining these arrows. Here's how I did it:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;import DirectionSet.{apply =&gt; _, _}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;case class Arrow(from: Direction, to: Direction) {&lt;br /&gt; override def toString = from+"-&gt;"+to&lt;br /&gt;} &lt;br /&gt;object Arrow {&lt;br /&gt; def apply(t: Tuple2[Direction,Direction]): Arrow = new Arrow(t._1, t._2)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Each arrow is described as going &lt;i&gt;from&lt;/i&gt; a &lt;i&gt;Direction&lt;/i&gt; &lt;i&gt;to&lt;/i&gt; another &lt;i&gt;Direction.&lt;/i&gt; A couple of helper methods, and we are done. At first, it might seem that the intersection being just a set of arrows, so it doesn't need a class of it's own. However, to validate the correctness of the maze I inputted, it would be nice to have a more "graphical" representation of it. I could leave that to the graph class, but, as it happens, it's a rather long code, so I separated it into a class of its own.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, first, I decided on the ASCII-art I'd be using to represent an intersection. I got it in as a literal, converted it into an array of arrays, and then, in the class main constructor, changed each relevant character from the ASCII-art into a space if the intersection didn't contain the corresponding arrow. The central character was a little bit more complex than that, and I used some pattern matching on it. Here's the final result:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;case class Intersection(arrows: List[Arrow]) {&lt;br /&gt; private val drawing = """|  ^ &lt;br /&gt;                          | /|\&lt;br /&gt;                          |&amp;lt;-+-&gt;&lt;br /&gt;                          | \|/&lt;br /&gt;                          |  v  """.stripMargin split "\n" map (_ toArray)&lt;br /&gt; private def hasUp = arrows exists (_.to == Up)&lt;br /&gt; private def hasDown = arrows exists (_.to == Down)&lt;br /&gt; private def hasLeft = arrows exists (_.to == Left)&lt;br /&gt; private def hasRight = arrows exists (_.to == Right)&lt;br /&gt; private def hasArrowBetween(a: Direction, b: Direction) = (arrows contains Arrow(a, b)) || (arrows contains Arrow(b, a))&lt;br /&gt; private def testAndSet(line: Int, col: Int, test: Boolean) =&lt;br /&gt;   if (!test) drawing(line)(col) = ' '&lt;br /&gt;&lt;br /&gt; testAndSet(0, 2, hasUp)&lt;br /&gt; testAndSet(1, 1, hasArrowBetween(Left, Up))&lt;br /&gt; testAndSet(1, 2, hasArrowBetween(Up, Down))&lt;br /&gt; testAndSet(1, 3, hasArrowBetween(Up, Right))&lt;br /&gt; testAndSet(2, 0, hasLeft)&lt;br /&gt; testAndSet(2, 1, hasArrowBetween(Left, Right))&lt;br /&gt; testAndSet(2, 3, hasArrowBetween(Left, Right))&lt;br /&gt; testAndSet(2, 4, hasRight)&lt;br /&gt; testAndSet(3, 1, hasArrowBetween(Left, Down))&lt;br /&gt; testAndSet(3, 2, hasArrowBetween(Up, Down))&lt;br /&gt; testAndSet(3, 3, hasArrowBetween(Down, Right))&lt;br /&gt; testAndSet(4, 2, hasDown)&lt;br /&gt; drawing(2)(2) = (hasArrowBetween(Left, Right), hasArrowBetween(Up, Down)) match {&lt;br /&gt;   case (false, false) =&gt; ' '&lt;br /&gt;   case (false, true) =&gt; '|'&lt;br /&gt;   case (true, false) =&gt; '-'&lt;br /&gt;   case (true, true) =&gt; '+'&lt;br /&gt; }&lt;br /&gt;  &lt;br /&gt; override def toString = drawing map (_ mkString) mkString "\n"&lt;br /&gt;}&lt;br /&gt;object Intersection {&lt;br /&gt; def apply(arrows: Arrow*): Intersection = new Intersection(arrows.toList)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The main class, the graph, started as simple as this:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;case class Graph(g: Array[Array[Intersection]])&lt;br /&gt;&lt;/pre&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;After that, I started on the parser. The first thing was breaking up the string into basic components: each line, each intersection on the line, the outgoing arrows and the edges:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;def brkString(s: String) = s.trim split "\n" map (_.trim split "," map (_.trim split ":"))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Lot's of "trim" just so I needn't worry where there were space. The next two steps were easy: for each line, for each intersection... It looks like a for-comprehension, but to return an array of arrays I'd need to nest two for-comprehensions, which makes them unyieldy. It's better simply to go with "map". So, given the input string representing each intersection, return an intersection instance. The mapping code ended looking like this:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;   (&lt;br /&gt;     brkString(s)&lt;br /&gt;     map (line =&gt;&lt;br /&gt;       line map (col =&gt;&lt;br /&gt;         Intersection(arrows(col): _*)&lt;br /&gt;       )&lt;br /&gt;     )&lt;br /&gt;   )&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Which leaves just "arrows" to be defined. The idea behind "arrows" is to convert each letter into a direction, then, for each direction representing an outgoing arrow, find all undirected edges containing that direction and yield a directed edge in the form of an Arrow instance:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;   def arrows(a: Array[String]): List[Arrow] = {&lt;br /&gt;     def str2Directions(s: String): List[Direction] = s map (DirectionSet(_)) toList&lt;br /&gt;     val dsts = str2Directions(a(0).trim)&lt;br /&gt;     val paths = a(1).trim split "\\s+" map str2Directions&lt;br /&gt;     for(dst &amp;lt;- dsts;&lt;br /&gt;         path &amp;lt;- paths if path contains dst;&lt;br /&gt;         org &amp;lt;- path filter (_ != dst))&lt;br /&gt;     yield Arrow(org, dst)&lt;br /&gt;   }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;These functions were all independent originally, but, as I refactored, they came to be part of the Graph object:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;object Graph {&lt;br /&gt; def apply(s: String) = new Graph(str2Graph(s))&lt;br /&gt;&lt;br /&gt; def str2Graph(s: String) = {&lt;br /&gt;   def brkString(s: String) = s.trim split "\n" map (_.trim split "," map (_.trim split ":"))&lt;br /&gt;   def arrows(a: Array[String]): List[Arrow] = {&lt;br /&gt;     def str2Directions(s: String): List[Direction] = s map (DirectionSet(_)) toList&lt;br /&gt;     val dsts = str2Directions(a(0).trim)&lt;br /&gt;     val paths = a(1).trim split "\\s+" map str2Directions&lt;br /&gt;     for(dst &amp;lt;- dsts;&lt;br /&gt;         path &amp;lt;- paths if path contains dst;&lt;br /&gt;         org &amp;lt;- path filter (_ != dst))&lt;br /&gt;     yield Arrow(org, dst)&lt;br /&gt;   }&lt;br /&gt;   (&lt;br /&gt;     brkString(s)&lt;br /&gt;     map (line =&gt;&lt;br /&gt;       line map (col =&gt;&lt;br /&gt;         Intersection(arrows(col): _*)&lt;br /&gt;       )&lt;br /&gt;     )&lt;br /&gt;   )&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;With that I could now create an instance of my graph. I could verify each intersection individually, but printing them side by side posed a problem: each intersection was composed of multiple lines, so I needed to interpolate the lines of all intersections belonging the the same "line" in the graph before I could concatenate them.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I approached this as a general problem in concatenating string with multiple lines. I'd split each string into its component lines, and keep a list of those. I'd then try to "fold" them into a big string, but that was too hacky for my tastes. I then modified it to iterate over these lists, concatenating the "heads" and looping with the "tails". Finally, I'd take each of those lines of intersection, and concatenate with interpoling newlines to the next. Here's the final result:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt; override def toString = {&lt;br /&gt;   def concatStrings(ss: String*) = {&lt;br /&gt;     // Turn my arguments into a list of lists of lines, get the length&lt;br /&gt;     // of the biggest chunk, a pad of the same size, and a function to&lt;br /&gt;     // make them all the same length&lt;br /&gt;     val lines = ss.toList map (_ split "\n" toList)&lt;br /&gt;     val maxLineSize = lines flatMap (_ map (_ length)) reduceLeft (_ max _)&lt;br /&gt;     val pad = " " * maxLineSize&lt;br /&gt;     def fmtStr(s: String) = "%"+maxLineSize+"s" format s&lt;br /&gt;&lt;br /&gt;     // Make an iterator for "lines"&lt;br /&gt;     def tailOrNil[T](l: List[T]) = if (l.isEmpty) Nil else l.tail&lt;br /&gt;     def getTails[T](l: List[List[T]]): List[List[T]] = l map tailOrNil[T]&lt;br /&gt;     def hasLines(l: List[List[_]]) = l exists (!_.isEmpty)&lt;br /&gt;     val linesIterator = Iterator.iterate(lines)(getTails) takeWhile hasLines&lt;br /&gt;&lt;br /&gt;     // Get the head of each list, or a pad in the absence of a head,&lt;br /&gt;     // make them all the same size, and then concatenate with an interpoling&lt;br /&gt;     // pad.&lt;br /&gt;     def concatHead(l: List[List[String]]): String =&lt;br /&gt;       l map (_.headOption getOrElse pad) map fmtStr mkString pad&lt;br /&gt;    &lt;br /&gt;     // Iterate over lines, concatenating the heads of the list, and then&lt;br /&gt;     // concatenate them all with interpolating newlines&lt;br /&gt;     (for(nextLines &amp;lt;- linesIterator)&lt;br /&gt;      yield concatHead(nextLines)) mkString "\n"&lt;br /&gt;   }&lt;br /&gt;   g map (line =&gt; concatStrings(line map (_ toString): _*)) mkString "\n\n\n"&lt;br /&gt; }&lt;br /&gt;&lt;/pre&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;You can tell by the amount of comments that I'm not really satisfied with it yet, but it does its job. Here's an example:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:text"&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;   &gt;     &amp;lt;   &gt;     &amp;lt;---      &amp;lt;---&gt;     &amp;lt;&lt;br /&gt;  /       \ /       \           /       \&lt;br /&gt; v         v                             v&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt; ^                   ^         ^         ^&lt;br /&gt;/|\       /|\        |\        |        /|&lt;br /&gt;-+-&gt;     &amp;lt;-+-&gt;     &amp;lt;-+-&gt;     &amp;lt;-+-&gt;     &amp;lt; |&lt;br /&gt; |        \|/       \|         |/        |&lt;br /&gt;           v         v         v&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt; ^         ^         ^         ^         ^&lt;br /&gt; |\         \       /|         |\        |&lt;br /&gt; | &gt;     &amp;lt;---&gt;       |         | &gt;       |&lt;br /&gt; |/       \ /       \|         |        \|&lt;br /&gt; v         v         v         v         v&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt; ^         ^         ^         ^         ^&lt;br /&gt; |\       / \       /|\       / \       /|&lt;br /&gt; | &gt;     &amp;lt;---&gt;      -+-&gt;     &amp;lt;---&gt;     &amp;lt; | &gt;&lt;br /&gt; |/         /        |/       \ /        |/&lt;br /&gt; v         v                             v&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt; ^         ^         ^         ^         ^&lt;br /&gt;  \       / \       / \       / \       /&lt;br /&gt;   &gt;     &amp;lt;---&gt;     &amp;lt;---&gt;     &amp;lt;---&gt;     &amp;lt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now I started on the solving algorithm properly. This part of it was rather faster and problem-free. First, I had to have a way to indicate where my car was. I created a class Position for that. This class has two components: one is the actual coordinates, indicating at which intersection the car had stopped -- I called it Coordinates. The other component is the direction from which the car was entering the intersection. Here's the class:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;case class Coordinates(line: Int, column: Int) {&lt;br /&gt; override def toString = "("+line+","+column+")"&lt;br /&gt;}&lt;br /&gt;case class Position(from: Direction, at: Coordinates) {&lt;br /&gt; override def toString = from.opposite.toString.toLowerCase+" to "+at&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;They didn't have any toString method originally. When I finally got to print the answer, I changed those methods to make the answer more readable.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Finally, I added a couple of methods to Graph. First, given a Position, to which directions the car could go? This one is quite natural:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt; def directionsFrom(pos: Position):List[Direction] = (&lt;br /&gt;   g(pos.at.line)(pos.at.column).arrows&lt;br /&gt;   filter (_.from == pos.from)&lt;br /&gt;   map (_.to)&lt;br /&gt; )&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;Next, given a Position, which would be the next available positions? This one required a helper method, which would compute the correct coordinates when moving in a given direction. I use "opposite" here. The idea is that, if I'm going "down", for example, I'd end at the upper side of the next intersection.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt; def positionsFrom(pos: Position): List[Position] = {&lt;br /&gt;   def moveTo(to: Direction) = Position(to.opposite, to match {&lt;br /&gt;       case Up =&gt; Coordinates(pos.at.line - 1, pos.at.column)&lt;br /&gt;       case Down =&gt; Coordinates(pos.at.line + 1, pos.at.column)&lt;br /&gt;       case Left =&gt; Coordinates(pos.at.line, pos.at.column - 1)&lt;br /&gt;       case Right =&gt; Coordinates(pos.at.line, pos.at.column + 1)&lt;br /&gt;   })&lt;br /&gt;   directionsFrom(pos) map moveTo&lt;br /&gt; }&lt;br /&gt;&lt;/pre&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;And, with that, we are ready to solve the problem. All we need to do is keep following the coordinates. Since I receive a list of coordinates at each intersection, I have to try all of them. There's two ways of going about it. First, I can take the first option out of each intersection and keep going, until I start looping around, get to a dead end, or arrive at my destination. I can then opt to backtrack and try one of the other options. That's a depth first algorithm, a natural for recursion.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Alternatively, I can keep a list of &lt;i&gt;all&lt;/i&gt; possible paths, and keep extending each one until one arrives. That can be done nicely with &lt;i&gt;queues&lt;/i&gt;. I take one path from the beginning of a queue, compute all possible paths from there, and add them to the back of the queue. Once I find a path that has arrived at the goal, I stop. This is what I decided to do. Here's the algorithm:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt; val graph = Graph(graphString)&lt;br /&gt; val origin = Position(Left, Coordinates(1, 0))&lt;br /&gt; val goal = Coordinates(3, 5)&lt;br /&gt;&lt;br /&gt; def solve = {&lt;br /&gt;   import scala.collection.mutable.{Set, Queue}&lt;br /&gt;  &lt;br /&gt;   def nextPaths(path: Path, visited: Set[Position]): List[Path] = (&lt;br /&gt;     graph&lt;br /&gt;     positionsFrom path.head&lt;br /&gt;     filter (to =&gt; !(visited contains to))&lt;br /&gt;     map (to =&gt; to :: path)&lt;br /&gt;   )&lt;br /&gt;   val visited = Set[Position]()&lt;br /&gt;   val next = new Queue[Path]()&lt;br /&gt;   var path = List(origin)&lt;br /&gt;   while(path.head.at != goal) {&lt;br /&gt;     visited += path.head&lt;br /&gt;     next enqueue (nextPaths(path, visited): _*)&lt;br /&gt;     path = next dequeue&lt;br /&gt;   }&lt;br /&gt;   printAnswer(path)&lt;br /&gt; }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;I still did a little trick to print the answer in a readable way, but it was hacky enough that I won't get into details. Here's the whole program, though. You can paste it directly into REPL and run it with "Problem.solve", or compile it and run Problem. So, how would you code this in YOUR favorite language? Please drop me a link on the comments below if you take this challenge too.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;object DirectionSet {&lt;br /&gt; sealed abstract class Direction {&lt;br /&gt;   def opposite: Direction&lt;br /&gt; }&lt;br /&gt; case object Up extends Direction { override def opposite = DirectionSet.Down }&lt;br /&gt; case object Down extends Direction { override def opposite = DirectionSet.Up }&lt;br /&gt; case object Left extends Direction { override def opposite = DirectionSet.Right }&lt;br /&gt; case object Right extends Direction { override def opposite = DirectionSet.Left }&lt;br /&gt; val U = Up&lt;br /&gt; val D = Down&lt;br /&gt; val L = Left&lt;br /&gt; val R = Right&lt;br /&gt; def apply(s: Char): Direction = s.toLowerCase match {&lt;br /&gt;   case 'u' =&gt; Up&lt;br /&gt;   case 'd' =&gt; Down&lt;br /&gt;   case 'l' =&gt; Left&lt;br /&gt;   case 'r' =&gt; Right&lt;br /&gt;   case _ =&gt; throw new IllegalArgumentException&lt;br /&gt; }&lt;br /&gt; def apply(s: String): Direction = s.toLowerCase match {&lt;br /&gt;   case "up" =&gt; Up&lt;br /&gt;   case "down" =&gt; Down&lt;br /&gt;   case "left" =&gt; Left&lt;br /&gt;   case "right" =&gt; Right&lt;br /&gt;   case _ =&gt; throw new IllegalArgumentException&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;import DirectionSet.{apply =&gt; _, _}&lt;br /&gt;&lt;br /&gt;case class Arrow(from: Direction, to: Direction) {&lt;br /&gt; override def toString = from+"-&gt;"+to&lt;br /&gt;} &lt;br /&gt;object Arrow {&lt;br /&gt; def apply(t: Tuple2[Direction,Direction]): Arrow = new Arrow(t._1, t._2)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;case class Intersection(arrows: List[Arrow]) {&lt;br /&gt; private val drawing = """|  ^ &lt;br /&gt;                          | /|\&lt;br /&gt;                          |&amp;lt;-+-&gt;&lt;br /&gt;                          | \|/&lt;br /&gt;                          |  v  """.stripMargin split "\n" map (_ toArray)&lt;br /&gt; private def hasUp = arrows exists (_.to == Up)&lt;br /&gt; private def hasDown = arrows exists (_.to == Down)&lt;br /&gt; private def hasLeft = arrows exists (_.to == Left)&lt;br /&gt; private def hasRight = arrows exists (_.to == Right)&lt;br /&gt; private def hasArrowBetween(a: Direction, b: Direction) = (arrows contains Arrow(a, b)) || (arrows contains Arrow(b, a))&lt;br /&gt; private def testAndSet(line: Int, col: Int, test: Boolean) =&lt;br /&gt;   if (!test) drawing(line)(col) = ' '&lt;br /&gt;&lt;br /&gt; testAndSet(0, 2, hasUp)&lt;br /&gt; testAndSet(1, 1, hasArrowBetween(Left, Up))&lt;br /&gt; testAndSet(1, 2, hasArrowBetween(Up, Down))&lt;br /&gt; testAndSet(1, 3, hasArrowBetween(Up, Right))&lt;br /&gt; testAndSet(2, 0, hasLeft)&lt;br /&gt; testAndSet(2, 1, hasArrowBetween(Left, Right))&lt;br /&gt; testAndSet(2, 3, hasArrowBetween(Left, Right))&lt;br /&gt; testAndSet(2, 4, hasRight)&lt;br /&gt; testAndSet(3, 1, hasArrowBetween(Left, Down))&lt;br /&gt; testAndSet(3, 2, hasArrowBetween(Up, Down))&lt;br /&gt; testAndSet(3, 3, hasArrowBetween(Down, Right))&lt;br /&gt; testAndSet(4, 2, hasDown)&lt;br /&gt; drawing(2)(2) = (hasArrowBetween(Left, Right), hasArrowBetween(Up, Down)) match {&lt;br /&gt;   case (false, false) =&gt; ' '&lt;br /&gt;   case (false, true) =&gt; '|'&lt;br /&gt;   case (true, false) =&gt; '-'&lt;br /&gt;   case (true, true) =&gt; '+'&lt;br /&gt; }&lt;br /&gt;  &lt;br /&gt; override def toString = drawing map (_ mkString) mkString "\n"&lt;br /&gt;}&lt;br /&gt;object Intersection {&lt;br /&gt; def apply(arrows: Arrow*): Intersection = new Intersection(arrows.toList)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;case class Coordinates(line: Int, column: Int) {&lt;br /&gt; override def toString = "("+line+","+column+")"&lt;br /&gt;}&lt;br /&gt;case class Position(from: Direction, at: Coordinates) {&lt;br /&gt; override def toString = from.opposite.toString.toLowerCase+" to "+at&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;case class Graph(g: Array[Array[Intersection]]) {&lt;br /&gt; def directionsFrom(pos: Position): List[Direction] = (&lt;br /&gt;   g(pos.at.line)(pos.at.column).arrows&lt;br /&gt;   filter (_.from == pos.from)&lt;br /&gt;   map (_.to)&lt;br /&gt; )&lt;br /&gt;&lt;br /&gt; def positionsFrom(pos: Position): List[Position] = {&lt;br /&gt;   def moveTo(to: Direction) = Position(to.opposite, to match {&lt;br /&gt;       case Up =&gt; Coordinates(pos.at.line - 1, pos.at.column)&lt;br /&gt;       case Down =&gt; Coordinates(pos.at.line + 1, pos.at.column)&lt;br /&gt;       case Left =&gt; Coordinates(pos.at.line, pos.at.column - 1)&lt;br /&gt;       case Right =&gt; Coordinates(pos.at.line, pos.at.column + 1)&lt;br /&gt;   })&lt;br /&gt;   directionsFrom(pos) map moveTo&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; override def toString = {&lt;br /&gt;   def concatStrings(ss: String*) = {&lt;br /&gt;     // Turn my arguments into a list of lists of lines, get the length&lt;br /&gt;     // of the biggest chunk, a pad of the same size, and a function to&lt;br /&gt;     // make them all the same length&lt;br /&gt;     val lines = ss.toList map (_ split "\n" toList)&lt;br /&gt;     val maxLineSize = lines flatMap (_ map (_ length)) reduceLeft (_ max _)&lt;br /&gt;     val pad = " " * maxLineSize&lt;br /&gt;     def fmtStr(s: String) = "%"+maxLineSize+"s" format s&lt;br /&gt;&lt;br /&gt;     // Make an iterator for "lines"&lt;br /&gt;     def tailOrNil[T](l: List[T]) = if (l.isEmpty) Nil else l.tail&lt;br /&gt;     def getTails[T](l: List[List[T]]): List[List[T]] = l map tailOrNil[T]&lt;br /&gt;     def hasLines(l: List[List[_]]) = l exists (!_.isEmpty)&lt;br /&gt;     val linesIterator = Iterator.iterate(lines)(getTails) takeWhile hasLines&lt;br /&gt;&lt;br /&gt;     // Get the head of each list, or a pad in the absence of a head,&lt;br /&gt;     // make them all the same size, and then concatenate with an interpoling&lt;br /&gt;     // pad.&lt;br /&gt;     def concatHead(l: List[List[String]]): String =&lt;br /&gt;       l map (_.headOption getOrElse pad) map fmtStr mkString pad&lt;br /&gt;    &lt;br /&gt;     // Iterate over lines, concatenating the heads of the list, and then&lt;br /&gt;     // concatenate them all with interpolating newlines&lt;br /&gt;     (for(nextLines &amp;lt;- linesIterator)&lt;br /&gt;      yield concatHead(nextLines)) mkString "\n"&lt;br /&gt;   }&lt;br /&gt;   g map (line =&gt; concatStrings(line map (_ toString): _*)) mkString "\n\n\n"&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;object Graph {&lt;br /&gt; def apply(s: String) = new Graph(str2Graph(s))&lt;br /&gt;&lt;br /&gt; def str2Graph(s: String) = {&lt;br /&gt;   def brkString(s: String) = s.trim split "\n" map (_.trim split "," map (_.trim split ":"))&lt;br /&gt;   def arrows(a: Array[String]): List[Arrow] = {&lt;br /&gt;     def str2Directions(s: String): List[Direction] = s map (DirectionSet(_)) toList&lt;br /&gt;     val dsts = str2Directions(a(0).trim)&lt;br /&gt;     val paths = a(1).trim split "\\s+" map str2Directions&lt;br /&gt;     for(dst &amp;lt;- dsts;&lt;br /&gt;         path &amp;lt;- paths if path contains dst;&lt;br /&gt;         org &amp;lt;- path filter (_ != dst))&lt;br /&gt;     yield Arrow(org, dst)&lt;br /&gt;   }&lt;br /&gt;   (&lt;br /&gt;     brkString(s)&lt;br /&gt;     map (line =&gt;&lt;br /&gt;       line map (col =&gt;&lt;br /&gt;         Intersection(arrows(col): _*)&lt;br /&gt;       )&lt;br /&gt;     )&lt;br /&gt;   )&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;object FormatLines {&lt;br /&gt; def apply(s: String): String = {&lt;br /&gt;   def breakAt80(s: String): (String, String) = {&lt;br /&gt;     val m = """^(.{0,80})( (.*))?$""".r findFirstMatchIn s&lt;br /&gt;     m match {&lt;br /&gt;       case Some(result) =&gt;&lt;br /&gt;       val rest = if (result.group(3) == null) "" else result.group(3)&lt;br /&gt;       (result.group(1), rest)&lt;br /&gt;       case None =&gt; (s, "")&lt;br /&gt;     }&lt;br /&gt;   }&lt;br /&gt;   def fmt(input: String, output: String): String =&lt;br /&gt;   if (input.isEmpty)&lt;br /&gt;   output&lt;br /&gt;   else {&lt;br /&gt;     val (nextLine, rest) = breakAt80(input)&lt;br /&gt;     fmt(rest, output+nextLine+"\n")&lt;br /&gt;   }&lt;br /&gt;   fmt(s, "")&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;object Problem {&lt;br /&gt; type Path = List[Position]&lt;br /&gt; val graphString = """|&lt;br /&gt;                      |DR: DR, RLD: RD LD, L: DL LR, LR: DR LR, DL: DL&lt;br /&gt;                      |UR: LU RU DU LR, LRD: LR UD LU RU LD RD, UDLR: UD LR UR LD, UDLR: UD LR RD, UL: UD UL&lt;br /&gt;                      |UDR: UD RU RD, UDLR: LR LD DR RU, UD: UD UL DL, UDR: UD UR, UD: UD LD&lt;br /&gt;                      |UDR: UD RU RD, UDLR: UR UL LR RD, UR: UD LR LU RU DR, ULR: LR UR UL DR DL, UDLR: UD UL DR&lt;br /&gt;                      |UR: UR, ULR: UL UR LR, ULR: UL UR RL, ULR: UL UR RL, UL: UL&lt;br /&gt;                      |""".stripMargin&lt;br /&gt; val graph = Graph(graphString)&lt;br /&gt; val origin = Position(Left, Coordinates(1, 0))&lt;br /&gt; val goal = Coordinates(3, 5)&lt;br /&gt;&lt;br /&gt; def printAnswer(path: Path) {&lt;br /&gt;   val answer = FormatLines(&lt;br /&gt;     "Arrived at "+path.head.at+&lt;br /&gt;     " through "+path.tail.reverse.mkString(", ")+&lt;br /&gt;     " and then "+path.head.from.opposite.toString.toLowerCase+"."&lt;br /&gt;   )&lt;br /&gt;   println(graph)&lt;br /&gt;   println(answer)&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; def solve = {&lt;br /&gt;   import scala.collection.mutable.{Set, Queue}&lt;br /&gt;  &lt;br /&gt;   def nextPaths(path: Path, visited: Set[Position]): List[Path] = (&lt;br /&gt;     graph&lt;br /&gt;     positionsFrom path.head&lt;br /&gt;     filter (to =&gt; !(visited contains to))&lt;br /&gt;     map (to =&gt; to :: path)&lt;br /&gt;   )&lt;br /&gt;   val visited = Set[Position]()&lt;br /&gt;   val next = new Queue[Path]()&lt;br /&gt;   var path = List(origin)&lt;br /&gt;   while(path.head.at != goal) {&lt;br /&gt;     visited += path.head&lt;br /&gt;     next enqueue (nextPaths(path, visited): _*)&lt;br /&gt;     path = next dequeue&lt;br /&gt;   }&lt;br /&gt;   printAnswer(path)&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; def main(args: Array[String]) {&lt;br /&gt;   solve&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-6735671050178839363?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/6735671050178839363/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/09/puzzle.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/6735671050178839363'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/6735671050178839363'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/09/puzzle.html' title='A Puzzle'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/_vHc2CW-BnIc/SqHI4EDVSiI/AAAAAAAAAJk/KXiU5tSFlAc/s72-c/carpuzzle.png' height='72' width='72'/><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-1791535081609734610</id><published>2009-08-17T18:39:00.006-03:00</published><updated>2009-08-17T18:45:22.159-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='regex'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Regex and Option trick</title><content type='html'>Neat trick:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;def findBetween(s: String, p1: String, p2: String) = (&lt;br /&gt;  ("\\Q"+p1+"\\E(.*?)\\Q"+p2+"\\E").r &lt;br /&gt;  findFirstMatchIn s &lt;br /&gt;  map (_ group 1) &lt;br /&gt;  getOrElse ""&lt;br /&gt;)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The trick here is that map, on an Option, applies the function if the option is Some, otherwise returns None. So I get to convert my Match into a particular group before I check if I got anything at all and return a default if not.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-1791535081609734610?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/1791535081609734610/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/08/regex-and-option-trick.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/1791535081609734610'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/1791535081609734610'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/08/regex-and-option-trick.html' title='Regex and Option trick'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-6445893925618026388</id><published>2009-07-19T20:11:00.004-03:00</published><updated>2009-07-19T20:21:38.056-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='software-engineering'/><title type='text'>Software Engineering -- An Idea Whose Time Has Gone?</title><content type='html'>That's a powerful statement over there. One I'd never dare state (aloud, at least :). They are not my words, though, they are Tony DeMarco's, who famously said "You can't control what you can't measure" in his book, &lt;i&gt;Controlling Software Projects: Management, Measurement, and Estimation&lt;/i&gt;, Prentice Hall/Yourdon Press, 1982.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Well, he hasn't changed his mind about &lt;i&gt;that&lt;/i&gt;, but he seems to have come to the conclusion that the relative value of that, particularly balanced against the costs of measuring -- which he once discounted -- is not what he once thought. You can read it on &lt;a href="http://www2.computer.org/cms/Computer.org/ComputingNow/homepage/2009/0709/rW_SO_Viewpoints.pdf"&gt;this IEEE-published article&lt;/a&gt;.&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-6445893925618026388?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/6445893925618026388/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/07/software-engineering-idea-whose-time.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/6445893925618026388'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/6445893925618026388'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/07/software-engineering-idea-whose-time.html' title='Software Engineering -- An Idea Whose Time Has Gone?'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-1889615587993349674</id><published>2009-07-07T15:51:00.002-03:00</published><updated>2009-07-07T16:16:15.797-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='type erasure'/><category scheme='http://www.blogger.com/atom/ns#' term='manifest'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Getting Around Type Erasure with Manifests</title><content type='html'>A friend posed an interesting problem to me yesterday. He wanted a registry-like structure in which he would put pairs of key/value, and then get them back. However, he wished for it to be type-safe. Specifically, if he put a List[Int] inside it, and tried to get a List[String] out, he shouldn’t get anything.&lt;br /&gt;&lt;br /&gt;This is generally a problem because of type erasure, a restriction of the JVM. At runtime, a List object knows it is a List, but not of what kind of element.&lt;br /&gt;&lt;br /&gt;Alas, an obscure, and experimental, feature of Scala let you get around that. It’s the Manifests. A Manifest is class whose instances are objects representing types. Since these instances are objects, you can pass them around, store them, and generally call methods on them. With the support of implicit parameters, it becomes a very powerful tool:&lt;br /&gt;&lt;pre class=”brush:scala”&gt;&lt;br /&gt;object Registry {&lt;br /&gt;  import scala.reflect.Manifest&lt;br /&gt;  &lt;br /&gt;  private var _map= Map.empty[Any,(Manifest[_], Any)] &lt;br /&gt;  &lt;br /&gt;  def register[T](name: Any, item: T)(implicit m: Manifest[T]) {&lt;br /&gt;    _map = _map(name) = (m, item)&lt;br /&gt;  }&lt;br /&gt;  &lt;br /&gt;  def get[T](key:Any)(implicit m : Manifest[T]): Option[T] = {&lt;br /&gt;    val o = _map.get(key)&lt;br /&gt;   &lt;br /&gt;    o match {&lt;br /&gt;      case Some((om: Manifest[_], s : Any)) =&gt;&lt;br /&gt;        if(om &amp;lt;:&amp;lt; m) Some(s.asInstanceOf[T]) else None&lt;br /&gt;      case _ =&gt; None&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;scala&gt; Registry.register('a, List(1,2,3))&lt;br /&gt;&lt;br /&gt;scala&gt; Registry.get[List[Int]]('a)&lt;br /&gt;res6: Option[List[Int]] = Some(List(1, 2, 3))&lt;br /&gt;&lt;br /&gt;scala&gt; Registry.get[List[String]]('a)&lt;br /&gt;res7: Option[List[String]] = None&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Above, Manifest is being passed as an implicit parameter – defined inside scala.reflect.Manifest – based on the type parameter T, and stored along the value. When you put a value in the register, it is not necessary to specify its type, as this gets inferred.&lt;br /&gt;&lt;br /&gt;When you take a registry out, though, you specify the type the type you want (inference won’t help you here), and, if the key does not exist or does not store the desired type, it will return None. If a key exists and the type is correct, it will return Some(value).&lt;br /&gt;&lt;br /&gt;Note that the operator &amp;lt;:&amp;lt; tests for subclassing. That is, the desired type m must be a superclass of the stored type om.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-1889615587993349674?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/1889615587993349674/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/07/getting-around-type-erasure-with.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/1889615587993349674'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/1889615587993349674'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/07/getting-around-type-erasure-with.html' title='Getting Around Type Erasure with Manifests'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-911503994452346448</id><published>2009-07-04T02:04:00.008-03:00</published><updated>2011-11-15T23:00:05.895-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='continuations'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Delimited Continuations Explained (in Scala)</title><content type='html'>One of the promised features for Scala 2.8 is a delimited continuations plugin. A &lt;a href="http://www.scala-lang.org/node/2096"&gt;brief description&lt;/a&gt; was given in the Scala site, though the examples were, in my opinion, badly chosen.&lt;br /&gt;&lt;br /&gt;Though my understanding is still pretty bare, I intend to shed a bit of light on it here. This is not directed at the experts, the people who will actually use them regularly, but at the people who will see them occasionally and will wonder what the heck is happening.  Also, I might quite possibly have made mistakes below. If you do find mistakes, please correct me and I’ll fix the post.&lt;br /&gt;&lt;br /&gt;First, let’s discuss &lt;em&gt;why&lt;/em&gt; Scala is adopting continuations, and what, exactly, are them.&lt;br /&gt;&lt;br /&gt;Continuations are, in essence, a program flow control structure, like conditional statements, loops, exceptions, etc. As mentioned in &lt;a href="http://lamp.epfl.ch/~rompf/continuations-icfp09.pdf"&gt; Scala’s  Continuations Paper&lt;/a&gt;, classical, or full, continuations can be seen as a functional version of GOTO statements. If you haven’t heard of GOTO statements before, it’s enough to know they are essentially extinct for good reason.&lt;br /&gt;&lt;br /&gt;Still quoting, delimited continuations are more like regular functions and less like GOTOs, and this makes them more powerful than the classical ones. So, basically, we are looking into a way of changing the execution flow of a program.&lt;br /&gt;&lt;br /&gt;Using continuations is not easy. In fact, it’s difficult and error-prone, according to some references. But they can be very efficient performance-wise, and they allow one to build libraries with some interesting flow control abstractions built on top of continuations.&lt;br /&gt;&lt;br /&gt;For these reasons, I doubt most Scala users will have much contact with them, and I suspect the ones who do will regret the necessity. The people writing libraries and frameworks, though, will likely be grateful that they are available. In that respect, continuation is not unlike some other advanced Scala features.&lt;br /&gt;&lt;br /&gt;Ok, so let’s get to them. In Scala, continuations will be used through two keywords (or functions?), “reset” and “shift”. Like “catch” and “throw”, a “shift” always happen inside a “reset”, the later being responsible for delimiting the scope of the continuation. Before we proceed, let’s give some usage examples, which I’ll then try to explain.&lt;br /&gt;&lt;br /&gt;Example 1:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;reset {&lt;br /&gt;shift { k: (Int=&amp;gt;Int) =&amp;gt;&lt;br /&gt; k(7)&lt;br /&gt;} + 1&lt;br /&gt;}&lt;br /&gt;// result: 8&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Example 2:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;def foo() = {&lt;br /&gt;println("Once here.")&lt;br /&gt;shift((k: Int =&amp;gt; Int) =&amp;gt; k(k(k(7))))&lt;br /&gt;}&lt;br /&gt;def bar() = {&lt;br /&gt;1+ foo()&lt;br /&gt;}&lt;br /&gt;def baz() = {&lt;br /&gt;reset(bar() * 2)&lt;br /&gt;}&lt;br /&gt;baz()  // result 70&lt;/pre&gt;&lt;br /&gt;Example 3:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;reset {&lt;br /&gt; println(1)&lt;br /&gt;}&lt;br /&gt;//prints: 1&lt;br /&gt;&lt;br /&gt;reset {&lt;br /&gt; println(1)&lt;br /&gt; shift { (cont: Unit =&amp;gt; Unit) =&amp;gt; }&lt;br /&gt; println(2)&lt;br /&gt;}&lt;br /&gt;//prints: 1&lt;br /&gt;&lt;br /&gt;reset {&lt;br /&gt; println(1)&lt;br /&gt; shift { (cont: Unit =&amp;gt; Unit) =&amp;gt;&lt;br /&gt;     println(2)&lt;br /&gt; }&lt;br /&gt; println(3)&lt;br /&gt;}&lt;br /&gt;//prints: 1 2&lt;br /&gt;&lt;br /&gt;reset {&lt;br /&gt; println(1)&lt;br /&gt; shift { (cont: Unit =&amp;gt; Unit) =&amp;gt;&lt;br /&gt;     cont()&lt;br /&gt;     println(2)&lt;br /&gt; }&lt;br /&gt; println(3)&lt;br /&gt;}&lt;br /&gt;//prints: 1 3 2&lt;br /&gt;&lt;br /&gt;reset {&lt;br /&gt; println(1)&lt;br /&gt; shift { (cont: Unit =&amp;gt; Unit) =&amp;gt;&lt;br /&gt;     cont()&lt;br /&gt;     cont()&lt;br /&gt;     println(2)&lt;br /&gt; }&lt;br /&gt; println(3)&lt;br /&gt;}&lt;br /&gt;//prints: 1 3 3 2&lt;/pre&gt;&lt;br /&gt;So we have two examples of continuations as expressions, and one as purely flow control. The first example seems pretty simple: the whole shift is replaced with “7”, and, therefore, reset returns “7+1”. The third example shows that, in fact, the code before shift is executed once, the code after shift as many times as the function inside shift is repeated, and the code inside the shift itself is executed once, going back and forth to the code after it.&lt;br /&gt;&lt;br /&gt;So we look at the second example, and see that… the code before shift seems to get executed many times! Actually, the method receiving the result of shift is being executed many times, once for each time “shift” return, but the statement right before shift only gets executed once.&lt;br /&gt;&lt;br /&gt;These examples were probably enough to… make things more confusing, right? So let’s understand what is happening. Scala’s continuations are based on a selective Continuation Passing Style (CPS) transformation. The Wikipedia page on &lt;a href="http://en.wikipedia.org/wiki/Continuation_passing_style"&gt;CPS&lt;/a&gt; is actually pretty good, so, please, take a moment to peruse it, and understand the examples given at the beginning, and then come back here.&lt;br /&gt;&lt;br /&gt;Ready? Well, one thing that immediately came to mind is that this looks like programming backwards! They call it “inside-out” in that page, which is more appropriate, I suppose, but one has to pay attention to first impressions. :-)&lt;br /&gt;&lt;br /&gt;What is happening there is that the innermost functions of normal programming style are outmost, and vice versa. You’ll see that this is what is happening with shift and reset.&lt;br /&gt;&lt;br /&gt;I’ll now explain a bit of what is happening in a continuation. Notice, first, that the code associated with the shifts are functions: they are all in the form { k =&amp;gt; … }. So, the first thing to keep in mind is that shifts are functions taking a parameter.&lt;br /&gt;&lt;br /&gt;Now, pay attention, again, to the very first example. It defines the type of k as being “Int =&amp;gt; Int”. In the first example, then, shift is a function which takes as parameter another function. This is actually true of all shifts, even if the function being passed to shift takes no parameters and returns Unit.&lt;br /&gt;&lt;br /&gt;So a shift is a function which receives another function as parameter. As the body of the shift gets executed, that function-parameter may get called or not. From the second example, it is pretty obvious that the code after the shift only gets executed if that function-parameter is called.&lt;br /&gt;&lt;br /&gt;By now you probably have an uneasy intuition that that parameter is, in fact, the code after the shift. That’s essentially right, but let’s further into this.&lt;br /&gt;&lt;br /&gt;The result of reset is the result of the code inside shift. So, in the first example, “8”, the result of reset, is also the result of the shift code, “k: (Int =&amp;gt; Int) =&amp;gt; k(7)”. It should be obvious, then, that the value passed to “k” is “x: Int =&amp;gt; x + 1”, which is a function of Int =&amp;gt; Int, as required. Now, take a look at the two lines below:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;shift { k: (Int=&amp;gt;Int) =&amp;gt; k(7) } + 1&lt;br /&gt;x                               + 1&lt;/pre&gt;&lt;br /&gt;So, the function being passed as parameter is formed by taking the whole code from the shift on, and replacing shift with “x”. In effect, when k(7) is executed, this is like replacing the whole shift with 7, and then continuing until the end of reset. At that point, though, the execution resumes inside the shift. In this example there is nothing more in there, so the result is 8.&lt;br /&gt;&lt;br /&gt;What is actually happening is this:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;((k: Int =&amp;gt; Int) =&amp;gt; k(7))((x: Int) =&amp;gt; x + 1)&lt;/pre&gt;&lt;br /&gt;As said before, we are passing a function to another. You can paste that code inside REPL and it will work as expected. You may also try this code here:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;((k: Int =&amp;gt; Int) =&amp;gt; k(k(k(7))))((x: Int) =&amp;gt; (1 + x) * 2)&lt;/pre&gt;&lt;br /&gt;Are you getting a feeling now for it? So, whenever you see reset/shift, first think of the whole reset expression, replacing the shift inside it with an unknown variable – we’ll keep calling it x for now:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt;Reset { before shift { k =&amp;gt; ... k(something) ... } after }&lt;br /&gt;Reset { before x after }&lt;/pre&gt;&lt;br /&gt;Now replace Reset with a function declaration of one parameter:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;Reset { before x after }&lt;br /&gt;x =&amp;gt; { before x after }&lt;/pre&gt;&lt;br /&gt;What type is “x” supposed to be? You can find it inside the shift, by looking into what is being passed to “k” – the “something” in the example. We can now rewrite the whole reset statement, placing first the shift code, then the reset code as parameter, like we did before:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt;( k =&amp;gt; ... k(something) ... ) {x =&amp;gt; { before x after }}&lt;/pre&gt;&lt;br /&gt;And this is pretty much what happens when you use continuations.&lt;br /&gt;&lt;br /&gt;As for the second example, though the “1 + “ looks to be to the “left” of shift, it actually gets executed after shift returns, so it is part of the function being passed to shift. You find the same situation when making tail recursive functions. If you tried “1 + recurse()”, it would not be tail recursive, because “+” would only be executed after the call to “recurse” returned.&lt;br /&gt;&lt;br /&gt;Pretty easy, right? Let’s try something with two shifts:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;type Monadic[+U, C[_]] = {&lt;br /&gt;def flatMap[V](f: U =&amp;gt; C[V]): C[V]&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Reflective[+A, C[_]](xs: Monadic[A,C]) {&lt;br /&gt;def reflect[B](): A @cps[C[B], C[B]] = {&lt;br /&gt; shift { k:(A =&amp;gt; C[B]) =&amp;gt;&lt;br /&gt;   xs.flatMap(k)&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;implicit def reflective[A](xs:Iterable[A]) =&lt;br /&gt;new Reflective[A,Iterable](xs)&lt;br /&gt;&lt;br /&gt;reset {&lt;br /&gt;val left = List("x","y","z")&lt;br /&gt;val right = List(4,5,6)&lt;br /&gt;&lt;br /&gt;List((left.reflect[Any], right.reflect[Any]))&lt;br /&gt;}&lt;br /&gt;// result: List[(String, Int)] = List((x,4), (x,5), (x,6), (y,4), (y,5), (y,6), (z,4), (z,5), (z,6)&lt;/pre&gt;&lt;br /&gt;Don’t hate me, it is in good cause. :-) If you can understand this… well, you can understand this. But I’m sure you’ll start to really get a grip in it.&lt;br /&gt;&lt;br /&gt;First, let’s discard the irrelevant parts of the code above. Everything but the “reflect” definition and the reset code is irrelevant. They are there just to make “reflect” available to a List, it’s plain-old Enrich My Library pattern, though the use of a structural type is cool. :-)&lt;br /&gt;&lt;br /&gt;Now, let’s replace left.reflect and right.reflect with the actual code getting executed – I’ll change k into k1 and k2 so as not to confuse both, so we are left only with the reset code:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;reset {&lt;br /&gt;val left = List("x","y","z")&lt;br /&gt;val right = List(4,5,6)&lt;br /&gt;&lt;br /&gt;List((shift { k1:(String =&amp;gt; List[Any]) =&amp;gt; left.flatMap(k1)}, shift { k2:(Int =&amp;gt; List[Any]) =&amp;gt; right.flatMap(k2)}))&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Since there are two shifts, should we have two unknowns being passed to shift? If you look at the type signatures for k1 and k2, the answer is no. Each shift gets a single parameter.&lt;br /&gt;&lt;br /&gt;You may think that the “Any” type means one list is formed by a single element, and the other by a tuple, but that’s not true. You can change both types to “List[(String,Int)]”, and it would still work. No, the type signatures are right, the trick is in how they are composed together.&lt;br /&gt;&lt;br /&gt;If you think it through simply in terms of flow control, the first shift will return a value (“x”), and then the second shift will return a value (4), producing a list. The flow then returns to the last shift, which will return another value (5),  and then another still (6). At this point, the flow returns once again to the first shift, which will produce it’s next value (“y”). So the trick is in how we compose the functions.&lt;br /&gt;&lt;br /&gt;Let’s see, first, both shifts:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;((k1: String =&amp;gt; List[(String,Int)]) =&amp;gt; left.flatMap(k1))&lt;br /&gt;((k2: Int =&amp;gt; List[(String,Int)]) =&amp;gt; right.flatMap(k2))&lt;/pre&gt;&lt;br /&gt;These can’t and won’t be changed. The trick is how we compose them:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;((k1: String =&amp;gt; List[(String,Int)]) =&amp;gt; left.flatMap(k1))&lt;br /&gt;((x: String) =&amp;gt; ((k2: Int =&amp;gt; List[(String,Int)]) =&amp;gt; right.flatMap(k2))&lt;br /&gt;             ((y: Int) =&amp;gt; List((x,y)))&lt;br /&gt;)&lt;/pre&gt;&lt;br /&gt;So what happens is that the function which takes a String and returns a List of (String,Int) that gets passed to the first shift is composed of &lt;em&gt;both&lt;/em&gt; the reset function &lt;em&gt;and&lt;/em&gt; the second shift function.&lt;br /&gt;&lt;br /&gt;The function passed to the second shift does not need an additional String parameter because the string is already bound.&lt;br /&gt;&lt;br /&gt;Now you have seen both the control flow of reset/shift, and how to translate them into common functions to understand what values they will produce. I hope it will be of help when the time comes in which you need to understand these structures.&lt;br /&gt;&lt;br /&gt;Note: many things have changed since I wrote this blog. Continuations have gone through minor changes in the annotations, and collections have gone through big changes. I haven't checked out all examples yet, but I know the one with the two lists doesn't work anymore. The following code will work for that example, though I wish I could make it more general than it presently is:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;type Monadic[+U, C[_]] = {&lt;br /&gt;  def flatMap[V, That](f: U =&amp;gt; C[V])(implicit cbf: collection.generic.CanBuildFrom[C[U], V, That]): That&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Reflective[+A](xs: Monadic[A,Traversable]) {&lt;br /&gt;  def reflect[B](): A @cps[Traversable[B]] = {&lt;br /&gt;    shift { k:(A =&amp;gt; Traversable[B]) =&amp;gt;&lt;br /&gt;      xs.flatMap(k)(collection.breakOut) : Traversable[B]&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;implicit def reflective[A](xs:Traversable[A]) = new Reflective[A](xs)&lt;br /&gt;&lt;br /&gt;reset {&lt;br /&gt;  val left = List("x","y","z")&lt;br /&gt;  val right = List(4,5,6)&lt;br /&gt;&lt;br /&gt;  List((left.reflect[Any], right.reflect[Any]))&lt;br /&gt;}&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-911503994452346448?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/911503994452346448/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/07/delimited-continuations-explained-in.html#comment-form' title='22 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/911503994452346448'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/911503994452346448'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/07/delimited-continuations-explained-in.html' title='Delimited Continuations Explained (in Scala)'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>22</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-524488840181629227</id><published>2009-07-02T17:29:00.002-03:00</published><updated>2011-11-15T22:58:35.536-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='matrix'/><category scheme='http://www.blogger.com/atom/ns#' term='beginner'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Matrices 6</title><content type='html'>In this last installment of the Matrices series, we’ll look into making the Matrix class parameterized. What does that means? Basically, we want to have Matrix declared like this:&lt;br /&gt;&lt;br /&gt;class Matrix[T]&lt;br /&gt;&lt;br /&gt;So that we can create matrices of Ints, Doubles, or whatever other numeric type we need. This is not a trivial exercise, because of the way numeric types are defined in Java, and Scala’s backward compatibility with it. Basically, there is no common superclass to them.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.blogger.com/profile/04844651950877109501"&gt;Paul Chisuano&lt;/a&gt;  offered two alternatives around that. One would involve the “Enrich My Library” pattern, but I do not think it would offer any gains over MatrixInt as it was built, and I see a problem or two implementing it.&lt;br /&gt;&lt;br /&gt;We’ll discuss the other solution he proposes, which is, indeed, very clever. If we were building this in Java, would idea would be creating an interface with the operations we need, and a concrete class for each type we need. For instance, let’s call our interface Scalar, and our concrete classes implementing it IntScalar, DoubleScalar, etc. We would then define a Matrix class parameterized with an “upper bound” of Scalar, created from an Array of Arrays of Scalar. That would work, but can be quite slow.&lt;br /&gt;&lt;br /&gt;Instead of that, we’ll use one of the more wizardry of Scala’s features, the implicit type conversion argument. You have probably seen things like this before:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt;implicit def xToY(x: X): Y = Y(x)&lt;/pre&gt;&lt;br /&gt;This definition makes it possible to convert an object of class X to an object of class Y without explicitly doing so. If I ever need an object of class Y and I have an object of class X instead, Scala will apply that definition to object X without any explicit statement on my part to do so.&lt;br /&gt;&lt;br /&gt;Even if you haven’t seen that before, you almost certainly have used it. See the two examples below:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt;scala&amp;gt; val a = 1.0; val b = 1&lt;br /&gt;a: Double = 1.0&lt;br /&gt;b: Int = 1&lt;br /&gt;&lt;br /&gt;scala&amp;gt; a + b&lt;br /&gt;res12: Double = 2.0&lt;br /&gt;&lt;br /&gt;scala&amp;gt; val c = Map('a -&amp;gt; 1)&lt;br /&gt;c: scala.collection.immutable.Map[Symbol,Int] = Map('a -&amp;gt; 1)&lt;/pre&gt;&lt;br /&gt;In each case, there is an implicit conversion at work. These definitions can, in fact, be found inside the object scala.Predef, which is imported automatically into scope of every Scala program. The first one is obvious, the second one, not so much. To understand the second, you have to realize that class Symbol does not define the method “-&amp;gt;”, and that “-&amp;gt;” is not a Scala keyword. I’ll leave as an exercise to find what implicit conversion is being used here.&lt;br /&gt;&lt;br /&gt;What that means for us is that we can create a Scalar class, as well as implicit conversions from our desired types to it. Scalar would look like this:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt;abstract class Scalar[T](self: T) {&lt;br /&gt; def +(other: T): T&lt;br /&gt; def -(other: T): T&lt;br /&gt; def /(other: T): T&lt;br /&gt; def %(other: T): T&lt;br /&gt; def *(other: T): T&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;One thing to note here is that none of the operations defined for Scalar take another Scalar as argument, nor do they return a Scalar. The reason for this is that we do not want to store Scalars. They are bulky and inefficient. We just want to quickly convert an Int or Double into Scalar, and then produce, through an Int or Double operation, and Int or Double result to be stored in an Array, or returned as result of determinant or similar methods.&lt;br /&gt;&lt;br /&gt;Even without implicits, we could define Matrix like this:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt;class Matrix[T](self: Array[Array[T]], toScalar: T =&amp;gt; Scalar[T])&lt;/pre&gt;&lt;br /&gt;We could then use toScalar everywhere we do an operation over a type T. With implicit, we could just add an implicit definition to the top of class Matrix, so we don’t need bother explicitly using toScalar. But we don’t need to do even that. Look at the following definition:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt;class Matrix[T](self: Array[Array[T]])(implicit toScalar: T =&amp;gt; Scalar[T])&lt;/pre&gt;&lt;br /&gt;This definition of Matrix constructor, with two sets of () for arguments, is said to be &lt;em&gt;curried&lt;/em&gt;. I won’t be explaining what that means here, because what interests us is the implicit keyword in there. The important thing here is that when you define something like that, then two things useful for us happen:&lt;br /&gt;&lt;br /&gt;1. If there is an implicit definition of the type “T =&amp;gt; Scalar[T]” in scope when we call Matrix, then it will be automatically passed to the constructor. Or, in other words, you can call “new Matrix(Array(Array(1)))” anywhere there is an implicit definition from Int to Scalar[Int], without having to pass that implicit definition as well.&lt;br /&gt;2. There is no need to define an implicit conversion inside Matrix itself. Any implicit conversion passed as an argument will already be used inside the class.&lt;br /&gt;&lt;br /&gt;This rule is also valid for implicit conversions arguments on method definitions, by the way.&lt;br /&gt;&lt;br /&gt;Anyway, this is so useful and powerful that Scala has another way of saying the same thing:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt;class Matrix[T &amp;lt;% Scalar[T]](self: Array[Array[T]])&lt;/pre&gt;&lt;br /&gt;The “&amp;lt;%” keyword means there should be an implicit conversion between the first type and the second in scope where Matrix constructor is called, or that one such conversion must be explicitly passed.&lt;br /&gt;&lt;br /&gt;So, we search&amp;amp;replace every instance of MatrixInt for Matrix[T], define our constructor as above (plus minor details such as “private” and “val”), replace Int with T where appropriate (remember that row and column coordinates are still Ints!), create the Scalar class, the subclasses for the types we want, the implicit conversions, and we are done, right?&lt;br /&gt;&lt;br /&gt;Not so.  Scalar, alas, is not enough. If you look at the definitions of sign, isDivisibleBy and invert, you will see we mix “T” with -1, 0 and 1. Since we do not know that -1, 0 and 1 can be mixed with “T”, we still need something else. Alas, what we need is actually very simple: an implicit definition between Int and T, so that when we use -1, it can be converted to the proper type, be it Int, Double or whatever.&lt;br /&gt;&lt;br /&gt;We have to be careful of one thing, though. See the two lines below:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt;map Function.tupled((value, col) =&amp;gt; value * cofactor(0, col).determinant * sign(0, col))&lt;br /&gt;map Function.tupled((value, col) =&amp;gt; sign(0, col) * value * cofactor(0, col).determinant)&lt;/pre&gt;&lt;br /&gt;The first line works, because it is converted into this:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt;map Function.tupled((value, col) =&amp;gt; toScalar(value) * toScalar(cofactor(0, col).determinant) * intToT(sign(0, col)))&lt;/pre&gt;&lt;br /&gt;The second line doesn’t work, as it would need to be converted into this:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt;map Function.tupled((value, col) =&amp;gt; toScalar(intToT(sign(0, col))) * toScalar(value) * cofactor(0, col).determinant)&lt;/pre&gt;&lt;br /&gt;On the first line there was at most one implicit conversion for each parameter. On the second line, though, since T doesn’t have the method “*”, and Int doesn’t have the method “*(T)”, two implicit conversions would need to be applied.&lt;br /&gt;&lt;br /&gt;Scala won’t apply two implicit conversions on the same element. In this case, we can make “sign” return T, so the extra implicit conversion will be applied inside “sign”, thus avoiding this rule. We need to be careful, however, about such situations. As it happens, MatrixInt, as it was written, won’t present any such problems.&lt;br /&gt;&lt;br /&gt;Anyway, we need, thus, two implicit conversions. The “&amp;lt;%” syntax isn’t enough for our particular case, so we have to do it the other way. Here’s our Matrix declaration:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt;class Matrix[T] private (private val self: Array[Array[T]])&lt;br /&gt;                       (implicit toScalar: T =&amp;gt; Scalar[T], intToT: Int =&amp;gt; T) {&lt;/pre&gt;&lt;br /&gt;Note that I write “implicit” only once in the declaration. All parameters in these last parentheses will be defined as implicit. Also, please note that implicit parameters must come last in such a declaration.&lt;br /&gt;&lt;br /&gt;This does take care of almost everything, with a bit of judicious editing on various declarations to make the signatures match. There are some places, though, where that is not the case. Look at these lines inside the method “toString”:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt;   val maxNumSize = self.projection flatMap (_ map (_.toString.size)) reduceLeft (_ max _)&lt;br /&gt;   val numFormat = "%"+maxNumSize+"d"&lt;br /&gt;   def formatNumber(n: T) = numFormat format n&lt;/pre&gt;&lt;br /&gt;We obviously can’t use “%d” for Doubles, for one thing. Also, maxNumSize doesn’t quite cut it, since we would like numbers to be aligned on the decimal point (or comma, depending on your locale), so we need to know at least two sizes. And then there are complex numbers, and who knows what else, so we don’t really know what information might be needed.&lt;br /&gt;&lt;br /&gt;Therefore, I feel it is better to leave the choice inside Scalar itself. I propose to add the method below to Scalar, define it for Int as shown next, and then use as show last:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt;abstract class Scalar[T](self: T) {&lt;br /&gt; ...&lt;br /&gt; def numFormat(xs: Iterator[T]): String&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class IntScalar(self: Int) extends Scalar(self) {&lt;br /&gt; ...&lt;br /&gt; def numFormat(xs: Iterator[Int]) = {&lt;br /&gt;   val maxNumSize = xs map (_.toString.size) reduceLeft (_ max _)&lt;br /&gt;   "%"+maxNumSize+"d"&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt; lazy val numFormat = this(0,0).numFormat(self flatMap (x =&amp;gt; x) elements)&lt;br /&gt; override def toString = {&lt;br /&gt;   def formatNumber(n: T) = numFormat format n&lt;br /&gt;   ...&lt;/pre&gt;&lt;br /&gt;It would have been more appropriate to define that method inside a companion object, but this way is simpler. Note, as well, that “numFormat” became a visible property, so we can re-use all this logic inside LinearEquations.&lt;br /&gt;&lt;br /&gt;Another place that needs fixing is inverse. We use the following rule:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt; lazy val inverse: Option[Matrix[T]] =&lt;br /&gt;   if (determinant == 0 || !isDivisibleBy(determinant))&lt;/pre&gt;&lt;br /&gt;Now, isDivisibleBy is implemented in terms of “%”, but that is just plain wrong for Double numbers. We could “fix” it by defining “%” to return 0, but that would make “%” act in a very unexpected way. So, instead, I’ll just define an “isDivisibleBy” operator inside Scalar:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt; def isDivisibleBy(other: T): Boolean&lt;/pre&gt;&lt;br /&gt;The last problem, as far as I can see, is with the equality methods. You’ll get erasure warnings in them if you use “Matrix[T]” on the case statement of equals or inside asInstanceOf on canEqual. Instead, use “Matrix[_]”, to indicate you don’t care what type T is. Since we are doing a deepEquals, T will sort itself out.&lt;br /&gt;&lt;br /&gt;The Scalar class and subclasses for Int and Double look like this:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt;abstract class Scalar[T](self: T) {&lt;br /&gt; def absolute: T&lt;br /&gt; def +(other: T): T&lt;br /&gt; def -(other: T): T&lt;br /&gt; def /(other: T): T&lt;br /&gt; def %(other: T): T&lt;br /&gt; def *(other: T): T&lt;br /&gt; def numFormat(xs: Iterator[T]): String&lt;br /&gt; override def numberSign: String&lt;br /&gt; def isDivisibleBy(other: T): Boolean&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class IntScalar(self: Int) extends Scalar(self) {&lt;br /&gt; override def absolute = self.abs&lt;br /&gt; override def +(other: Int) = self + other&lt;br /&gt; override def -(other: Int) = self - other&lt;br /&gt; override def /(other: Int) = self / other&lt;br /&gt; override def %(other: Int) = self % other&lt;br /&gt; override def *(other: Int) = self * other&lt;br /&gt; override def numFormat(xs: Iterator[Int]) = {&lt;br /&gt;   val maxNumSize = xs.map(_.toString.size).foldLeft(0)(_ max _)&lt;br /&gt;   "%"+maxNumSize+"d"&lt;br /&gt; }&lt;br /&gt; override def numberSign = if (self &amp;lt; 0) "-" else "+"&lt;br /&gt; override def isDivisibleBy(other: Int) = (self % other) == 0&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class DoubleScalar(self: Double) extends Scalar(self) {&lt;br /&gt; override def absolute = self.abs&lt;br /&gt; override def +(other: Double) = self + other&lt;br /&gt; override def -(other: Double) = self - other&lt;br /&gt; override def /(other: Double) = self / other&lt;br /&gt; override def %(other: Double) = self % other&lt;br /&gt; override def *(other: Double) = self * other&lt;br /&gt; override def numFormat(xs: Iterator[Double]) = {&lt;br /&gt;   val numbers = xs.toList&lt;br /&gt;   val maxIntSize = (&lt;br /&gt;     numbers&lt;br /&gt;     .map(_.toString.takeWhile(c =&amp;gt; c != '.' &amp;amp;&amp;amp; c != ',').length)&lt;br /&gt;     .foldLeft(0)(_ max _)&lt;br /&gt;   )&lt;br /&gt;   val maxDecimalSize = (&lt;br /&gt;     numbers&lt;br /&gt;     .map(_.toString.dropWhile(c =&amp;gt; c != '.' &amp;amp;&amp;amp; c != ',').length)&lt;br /&gt;     .foldLeft(0)(_ max _)&lt;br /&gt;   ) - 1&lt;br /&gt;   "%"+maxIntSize+"."+maxDecimalSize+"f"&lt;br /&gt; }&lt;br /&gt; override def numberSign = if (self &amp;lt; 0) "-" else "+"&lt;br /&gt; override def isDivisibleBy(other: Double) = true&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Note that we transform “xs” into a List inside DoubleScalar. That’s because we are iterating through it twice, which isn’t possible with an Iterator. Also note we added “absolute” and “numberSign”, which are used by LinearEquations.&lt;br /&gt;&lt;br /&gt;The method “absolute” is not called “abs”, though, because “abs” is defined on RichInt, RichDouble, etc. So if we defined it for IntScalar, and then tried to use “abs” on an Int, the compiler would not know whether to use RichInt’s abs or IntScala’s abs.&lt;br /&gt;&lt;br /&gt;We’ll also add the following two lines to the Matrix companion-object:&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt; implicit def intToScalar(n: Int): Scalar[Int] = new IntScalar(n)&lt;br /&gt; implicit def doubleToScalar(n: Double): Scalar[Double] = new DoubleScalar(n)&lt;/pre&gt;&lt;br /&gt;This way these two types, Int and Double, will automatically become available after importing “Matrix._”. The user can arbitrarily extend Matrix to cover any type, though, by creating a subclass of Scalar and defining an implicit conversion from the desired type to it.&lt;br /&gt;&lt;br /&gt;Performance-wise, the boxing of the numeric types for each operation is detrimental, but it can probably be optimized by either the compiler or the JIT. In Scala 2.8 there will also be the option of marking a class “specialized”, which is creates specially optimized versions of a class for Java’s “primitive” types. I’m not sure it applies in this situation, though.&lt;br /&gt;&lt;br /&gt;I’ll finish with the revised code for Matrix. If you have any questions or suggestions, please send them to me and I’ll try to address them. I hope you found this series useful!&lt;br /&gt;&lt;pre class="”brush:scala”"&gt;&lt;br /&gt;class Matrix[T] private (private val self: Array[Array[T]])&lt;br /&gt;                       (implicit toScalar: T =&amp;gt; Scalar[T], intToT: Int =&amp;gt; T) {&lt;br /&gt; import Matrix._&lt;br /&gt;&lt;br /&gt; val rows = self.size&lt;br /&gt; val cols = self(0).size&lt;br /&gt;&lt;br /&gt; private def _row(n: Int): Array[T] = self(n)&lt;br /&gt; private def _col(n: Int): Array[T] = self map (_(n))&lt;br /&gt;&lt;br /&gt; def row(n: Int): Array[T] = _row(n) map (x =&amp;gt; x)&lt;br /&gt; def col(n: Int): Array[T] = _col(n)&lt;br /&gt;&lt;br /&gt; def apply(i: Int, j: Int): T =&lt;br /&gt;   if (i &amp;gt;= rows || j &amp;gt;= cols || i &amp;lt; 0 || j &amp;lt; 0)&lt;br /&gt;     throw new IndexOutOfBoundsException&lt;br /&gt;   else&lt;br /&gt;     self(i)(j)&lt;br /&gt;&lt;br /&gt; def update(row: Int, col: Int, newValue: T): Matrix[T] =&lt;br /&gt;   new Matrix(createArrays(rows, cols, (i,j) =&amp;gt;&lt;br /&gt;     if (row == i &amp;amp;&amp;amp; col == j) newValue else this(i,j)))&lt;br /&gt;&lt;br /&gt; def update(what: Dimension, where: Int, newValue: Array[T]): Matrix[T] =&lt;br /&gt;   what match {&lt;br /&gt;     case Row =&amp;gt; replaceRow(where, newValue)&lt;br /&gt;     case Column =&amp;gt; replaceCol(where, newValue)&lt;br /&gt;   }&lt;br /&gt;    &lt;br /&gt; def replaceCol(col: Int, newValue: Array[T]): Matrix[T] =&lt;br /&gt;   new Matrix(createArrays(rows, cols, (i,j) =&amp;gt;&lt;br /&gt;     if (col == j) newValue(i) else this(i,j)))&lt;br /&gt;&lt;br /&gt; def replaceRow(row: Int, newValue: Array[T]): Matrix[T] =&lt;br /&gt;   new Matrix(createArrays(rows, cols, (i,j) =&amp;gt;&lt;br /&gt;     if (row == i) newValue(j) else this(i,j)))&lt;br /&gt;&lt;br /&gt; override def equals(other: Any): Boolean = other match {&lt;br /&gt;   case that: Matrix[_] =&amp;gt;&lt;br /&gt;     that.canEqual(this) &amp;amp;&amp;amp; self.deepEquals(that.self)&lt;br /&gt;   case _ =&amp;gt; false&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; def canEqual(other: Any): Boolean = other.isInstanceOf[Matrix[_]]&lt;br /&gt;  &lt;br /&gt; def *(n: T): Matrix[T] =&lt;br /&gt;   new Matrix(createArrays(rows, cols, (row, col) =&amp;gt; this(row,col) * n))&lt;br /&gt;&lt;br /&gt; def /(n: T): Matrix[T] =&lt;br /&gt;   new Matrix(createArrays(rows, cols, (row, col) =&amp;gt; this(row,col) / n))&lt;br /&gt;&lt;br /&gt; def %(n: T): Matrix[T] =&lt;br /&gt;   new Matrix(createArrays(rows, cols, (row, col) =&amp;gt; this(row,col) % n))&lt;br /&gt;&lt;br /&gt; def +(other: Matrix[T]): Matrix[T] =&lt;br /&gt;   if (rows != other.rows || cols != other.cols)&lt;br /&gt;     throw new IllegalArgumentException&lt;br /&gt;   else&lt;br /&gt;     new Matrix(createArrays(rows, cols, (row, col) =&amp;gt; this(row,col) + other(row,col)))&lt;br /&gt;&lt;br /&gt; def -(other: Matrix[T]): Matrix[T] =&lt;br /&gt;   if (rows != other.rows || cols != other.cols)&lt;br /&gt;     throw new IllegalArgumentException&lt;br /&gt;   else&lt;br /&gt;     new Matrix(createArrays(rows, cols, (row, col) =&amp;gt; this(row,col) - other(row, col)))&lt;br /&gt;&lt;br /&gt; def *(other: Matrix[T]): Matrix[T] =&lt;br /&gt;   if (cols != other.rows)&lt;br /&gt;     throw new IllegalArgumentException&lt;br /&gt;   else&lt;br /&gt;     new Matrix(createArrays(rows, other.cols, (row, col) =&amp;gt;&lt;br /&gt;       this._row(row) zip other._col(col) map Function.tupled(_*_) reduceLeft (_+_)&lt;br /&gt;     ))&lt;br /&gt;&lt;br /&gt; def **(n: Int): Matrix[T] =&lt;br /&gt;   if (rows != cols)&lt;br /&gt;     throw new UnsupportedOperationException&lt;br /&gt;   else n match {&lt;br /&gt;     case 0 =&amp;gt; unitMatrix(rows)&lt;br /&gt;     case 1 =&amp;gt; this&lt;br /&gt;     case 2 =&amp;gt; this * this&lt;br /&gt;     case negative if negative &amp;lt; 0 =&amp;gt;&lt;br /&gt;       (this ** negative.abs).inverse getOrElse (throw new UnsupportedOperationException)&lt;br /&gt;     case odd if odd % 2 == 1 =&amp;gt; this ** (odd - 1) * this&lt;br /&gt;     case even =&amp;gt; this ** (even / 2) ** 2&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt; def toArray = Matrix.clone(self)&lt;br /&gt;&lt;br /&gt; def transpose = new Matrix(createArrays(cols, rows, (row,col) =&amp;gt; this(col,row)))&lt;br /&gt;&lt;br /&gt; def cofactor(row: Int, col: Int) = new Matrix(createArrays(rows-1, cols-1, (i,j) =&amp;gt;&lt;br /&gt;   this(i + (if (i &amp;lt; row) 0 else 1), j + (if (j &amp;lt; col) 0 else 1))))&lt;br /&gt;&lt;br /&gt; protected def sign(row: Int, col: Int): T = if ((col + row) % 2 == 0) 1 else -1&lt;br /&gt;&lt;br /&gt; lazy val determinant: T =&lt;br /&gt;   if (rows != cols)&lt;br /&gt;     throw new UnsupportedOperationException&lt;br /&gt;   else rows match {&lt;br /&gt;     case 1 =&amp;gt; this(0,0)&lt;br /&gt;     case 2 =&amp;gt; this(0,0)*this(1,1) - this(1,0)*this(0,1)&lt;br /&gt;     case n =&amp;gt; (&lt;br /&gt;       _row(0).zipWithIndex&lt;br /&gt;       map Function.tupled((value, col) =&amp;gt; value * cofactor(0, col).determinant * sign(0, col))&lt;br /&gt;       reduceLeft (_+_)&lt;br /&gt;       )&lt;br /&gt;     }&lt;br /&gt;&lt;br /&gt; def minor(row: Int, col: Int) = cofactor(row, col).determinant&lt;br /&gt;&lt;br /&gt; lazy val adjugate: Matrix[T] = new Matrix(createArrays(cols, rows, (row, col) =&amp;gt;&lt;br /&gt;   minor(col, row) * sign(col, row)&lt;br /&gt; ))&lt;br /&gt;&lt;br /&gt; def isDivisibleBy(n: T): Boolean =&lt;br /&gt;   self flatMap (row =&amp;gt; row) forall (_ isDivisibleBy n)&lt;br /&gt;&lt;br /&gt; lazy val inverse: Option[Matrix[T]] =&lt;br /&gt;   if (determinant == 0 || !isDivisibleBy(determinant))&lt;br /&gt;     None&lt;br /&gt;   else&lt;br /&gt;     Some(adjugate / determinant)&lt;br /&gt;&lt;br /&gt; lazy val numFormat = this(0,0).numFormat(self flatMap (x =&amp;gt; x) elements)&lt;br /&gt;&lt;br /&gt; override def toString = {&lt;br /&gt;   val numFormat = this(0,0).numFormat(self flatMap (x =&amp;gt; x) elements)&lt;br /&gt;   def formatNumber(n: T) = numFormat format n&lt;br /&gt;   val top = rows match {&lt;br /&gt;     case 1 =&amp;gt; _row(0) map formatNumber mkString ("&amp;lt; ", " ", " &amp;gt;")&lt;br /&gt;     case _ =&amp;gt; _row(0) map formatNumber mkString ("/ ", " ", " \\") // Fix highlighter: "&lt;br /&gt;   }&lt;br /&gt;   val middle = rows match {&lt;br /&gt;     case 1 | 2 =&amp;gt; Nil&lt;br /&gt;     case _ =&amp;gt; self.toList.tail.init map (_ map formatNumber mkString("| "," "," |"))&lt;br /&gt;   }&lt;br /&gt;   val bottom = rows match {&lt;br /&gt;     case 1 =&amp;gt; Nil&lt;br /&gt;     case _ =&amp;gt; List(_row(rows - 1) map formatNumber mkString ("\\ ", " ", " /"))&lt;br /&gt;   }&lt;br /&gt;  &lt;br /&gt;   top :: middle ::: bottom mkString "\n"&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;object Matrix {&lt;br /&gt; import Matrix._&lt;br /&gt; implicit def toMatrix[T](m : Array[Array[T]])&lt;br /&gt;                         (implicit toScalar: T =&amp;gt; Scalar[T], intToT: Int =&amp;gt; T) = Matrix(m)&lt;br /&gt;&lt;br /&gt; def apply[T](array: Array[Array[T]])&lt;br /&gt;             (implicit toScalar: T =&amp;gt; Scalar[T], intToT: Int =&amp;gt; T): Matrix[T] =&lt;br /&gt;   new Matrix(clone(array))&lt;br /&gt; def apply[T](rows: Int, cols: Int)&lt;br /&gt;             (implicit toScalar: T =&amp;gt; Scalar[T], intToT: Int =&amp;gt; T): Matrix[T] =&lt;br /&gt;   Matrix(rows, cols, 0)&lt;br /&gt; def apply[T](rows: Int, cols: Int, value: T)&lt;br /&gt;             (implicit toScalar: T =&amp;gt; Scalar[T], intToT: Int =&amp;gt; T): Matrix[T] =&lt;br /&gt;   new Matrix(createArrays(rows, cols, ((_,_) =&amp;gt; value)))&lt;br /&gt; def apply[T](rows: Int, cols: Int, f: (Int,Int) =&amp;gt; T)&lt;br /&gt;             (implicit toScalar: T =&amp;gt; Scalar[T], intToT: Int =&amp;gt; T): Matrix[T] =&lt;br /&gt;   new Matrix(createArrays(rows, cols, f))&lt;br /&gt;&lt;br /&gt; def unitMatrix[T](n: Int)(implicit toScalar: T =&amp;gt; Scalar[T], intToT: Int =&amp;gt; T) =&lt;br /&gt;   Matrix[T](n, n, (row: Int,col: Int) =&amp;gt; (if (row == col) intToT(1) else intToT(0)))&lt;br /&gt;&lt;br /&gt; protected def createArrays[T](rows: Int, cols: Int, f: (Int, Int) =&amp;gt; T) =&lt;br /&gt;   for((i: Int) &amp;lt;- (0 until rows).toArray)&lt;br /&gt;     yield for((j: Int) &amp;lt;- (0 until cols).toArray)&lt;br /&gt;       yield f(i,j)&lt;br /&gt;&lt;br /&gt; protected def clone[T](a: Array[Array[T]]) =&lt;br /&gt;   createArrays(a.size, a(0).size, (row, col) =&amp;gt; a(row)(col))&lt;br /&gt;  &lt;br /&gt; sealed abstract class Dimension&lt;br /&gt; case object Row extends Dimension&lt;br /&gt; case object Column extends Dimension&lt;br /&gt;&lt;br /&gt; implicit def intToScalar(n: Int): Scalar[Int] = new IntScalar(n)&lt;br /&gt; implicit def doubleToScalar(n: Double): Scalar[Double] = new DoubleScalar(n)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class LinearEquations[T](val m: Matrix[T], val r: Matrix[T])&lt;br /&gt;                       (implicit toScalar: T =&amp;gt; Scalar[T], intToT: Int =&amp;gt; T) {&lt;br /&gt; require(m.rows == r.rows &amp;amp;&amp;amp; r.cols == 1)&lt;br /&gt;&lt;br /&gt; def maxColumnSize(matrix: Matrix[T], isAbs: Boolean): Int = (&lt;br /&gt;   matrix.toArray&lt;br /&gt;   flatMap (row =&amp;gt; row)&lt;br /&gt;   map (value =&amp;gt; (if (isAbs) value.absolute else value).toString.length)&lt;br /&gt;   reduceLeft (_ max _)&lt;br /&gt; )&lt;br /&gt;&lt;br /&gt; lazy val maxColsSize = m.cols.toString.length&lt;br /&gt;&lt;br /&gt; def numberSign(n: T) = " %s " format n.numberSign&lt;br /&gt; def formatConstant(n: T) = r.numFormat format n&lt;br /&gt; def formatCoefficient(n: T) = m.numFormat format n.absolute&lt;br /&gt; def formatUnknown(index: Int) = "x("+("%0"+maxColsSize+"d" format index)+")"&lt;br /&gt;&lt;br /&gt; // On Scala 2.8, replace drop(1) with tail and first with head below&lt;br /&gt; def formatLine(coefficients: Array[T],&lt;br /&gt;                constant: T,&lt;br /&gt;                printUnknown: Int =&amp;gt; String) =&lt;br /&gt;   coefficients&lt;br /&gt;   .zipWithIndex&lt;br /&gt;   .drop(1)&lt;br /&gt;   .foldLeft(formatCoefficient(coefficients.first)+printUnknown(0))(&lt;br /&gt;     (x,y) =&amp;gt; x+numberSign(y._1)+formatCoefficient(y._1)+printUnknown(y._2)&lt;br /&gt;   )+" = "+formatConstant(constant)&lt;br /&gt;&lt;br /&gt; def makeString(printUnknown: Int =&amp;gt; String) = (&lt;br /&gt;   for(row &amp;lt;- 0 until m.rows)&lt;br /&gt;   yield formatLine(m.row(row), r(row,0), printUnknown)&lt;br /&gt; ).mkString("\n")&lt;br /&gt;  &lt;br /&gt; override def toString = makeString(formatUnknown)&lt;br /&gt;&lt;br /&gt; def getUnknowns(u: Matrix[T]): Int =&amp;gt; String =&lt;br /&gt;   (index: Int) =&amp;gt; " * "+(u.numFormat format u(index,0))&lt;br /&gt;&lt;br /&gt; lazy val solutionInverse: Option[Matrix[T]] =&lt;br /&gt;   if (m.inverse == None)&lt;br /&gt;     None&lt;br /&gt;   else&lt;br /&gt;     Some(m.inverse.get * r)&lt;br /&gt;&lt;br /&gt; def solveInverse =&lt;br /&gt;   if (solutionInverse == None)&lt;br /&gt;     "There is no unique solution"&lt;br /&gt;   else&lt;br /&gt;     makeString(getUnknowns(solutionInverse.get))&lt;br /&gt;&lt;br /&gt; lazy val solutionCramer: Option[Matrix[T]] = {&lt;br /&gt;   val vector = r.toArray.flatMap(x =&amp;gt; x)&lt;br /&gt;   if (m.determinant == 0)&lt;br /&gt;     None&lt;br /&gt;   else&lt;br /&gt;     Some(Matrix(&lt;br /&gt;       for((col: Int) &amp;lt;- (0 until m.cols).toArray)&lt;br /&gt;       yield for(row &amp;lt;- Array(0)) // Array[T](...) doesn't work, as it requires T &amp;lt;: AnyRef&lt;br /&gt;         yield m.replaceCol(col, vector).determinant / m.determinant&lt;br /&gt;     ))&lt;br /&gt; }&lt;br /&gt;    &lt;br /&gt; def solveCramer =&lt;br /&gt;   if (solutionCramer == None)&lt;br /&gt;     "There is no unique solution"&lt;br /&gt;   else&lt;br /&gt;     makeString(getUnknowns(solutionCramer.get))&lt;br /&gt;}&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-524488840181629227?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/524488840181629227/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/07/matrices-6.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/524488840181629227'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/524488840181629227'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/07/matrices-6.html' title='Matrices 6'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-6032759089382990855</id><published>2009-07-01T20:53:00.003-03:00</published><updated>2009-07-01T20:57:16.571-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='matrix'/><category scheme='http://www.blogger.com/atom/ns#' term='beginner'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Matrices 5b</title><content type='html'>To finish my last post I wrote a quick&amp;dirty class to show MatrixInt in use. Alas, it was so dirty I couldn't stand the shame, so I rewrote it. Have fun. :-)&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;class LinearEquations(val m: MatrixInt, val r: MatrixInt) {&lt;br /&gt;  require(m.rows == r.rows &amp;&amp; r.cols == 1)&lt;br /&gt;  &lt;br /&gt;  def maxColumnSize(matrix: MatrixInt, isAbs: Boolean): Int = (&lt;br /&gt;    matrix.toArray &lt;br /&gt;    flatMap (row =&gt; row) &lt;br /&gt;    map (value =&gt; (if (isAbs) value.abs else value).toString.length)&lt;br /&gt;    reduceLeft (_ max _)&lt;br /&gt;  )&lt;br /&gt;  &lt;br /&gt;  lazy val maxCoefficientsColumnSize =  maxColumnSize(m, true)&lt;br /&gt;  lazy val maxConstantsColumnSize = maxColumnSize(r, false)&lt;br /&gt;  lazy val maxColsSize = m.cols.toString.length&lt;br /&gt;  &lt;br /&gt;  def numberSign(n: Int) = if (n &amp;lt; 0) " - " else " + "&lt;br /&gt;  def formatNumber(n: Int, size: Int) = "%"+size+"d" format n&lt;br /&gt;  def formatConstant(n: Int) = formatNumber(n, maxConstantsColumnSize)&lt;br /&gt;  def formatCoefficient(n: Int) = formatNumber(n.abs, maxCoefficientsColumnSize)&lt;br /&gt;  def formatUnknown(index: Int) = "x("+("%0"+maxColsSize+"d" format index)+")"&lt;br /&gt;  &lt;br /&gt;  // On Scala 2.8, replace drop(1) with tail and first with head below&lt;br /&gt;  def formatLine(coefficients: Array[Int], &lt;br /&gt;                 constant: Int, &lt;br /&gt;                 printUnknown: Int =&gt; String) =&lt;br /&gt;    coefficients&lt;br /&gt;    .zipWithIndex&lt;br /&gt;    .drop(1)&lt;br /&gt;    .foldLeft(formatCoefficient(coefficients.first)+printUnknown(0))(&lt;br /&gt;      (x,y) =&gt; x+numberSign(y._1)+formatCoefficient(y._1)+printUnknown(y._2)&lt;br /&gt;    )+" = "+formatConstant(constant)&lt;br /&gt;&lt;br /&gt;  def makeString(printUnknown: Int =&gt; String) = (&lt;br /&gt;    for(row &amp;lt;- 0 until m.rows)&lt;br /&gt;    yield formatLine(m.row(row), r(row,0), printUnknown)&lt;br /&gt;  ).mkString("\n")&lt;br /&gt;    &lt;br /&gt;  override def toString = makeString(formatUnknown)&lt;br /&gt;  &lt;br /&gt;  def getUnknowns(u: MatrixInt): Int =&gt; String =&lt;br /&gt;    (index: Int) =&gt; " * "+u(index,0)&lt;br /&gt;&lt;br /&gt;  lazy val solutionInverse: Option[MatrixInt] =&lt;br /&gt;    if (m.inverse == None)&lt;br /&gt;      None&lt;br /&gt;    else&lt;br /&gt;      Some(m.inverse.get * r) &lt;br /&gt;&lt;br /&gt;  def solveInverse =&lt;br /&gt;    if (solutionInverse == None)&lt;br /&gt;      "There is no unique solution"&lt;br /&gt;    else&lt;br /&gt;      makeString(getUnknowns(solutionInverse.get)) &lt;br /&gt;&lt;br /&gt;  lazy val solutionCramer: Option[MatrixInt] = {&lt;br /&gt;    val vector = r.toArray.flatMap(x =&gt; x)&lt;br /&gt;    if (m.determinant == 0)&lt;br /&gt;      None&lt;br /&gt;    else&lt;br /&gt;      Some(MatrixInt(&lt;br /&gt;        for((col: Int) &amp;lt;- (0 until m.cols).toArray)&lt;br /&gt;        yield Array(&lt;br /&gt;            m.replaceCol(col, vector).determinant / m.determinant &lt;br /&gt;          )&lt;br /&gt;      ))&lt;br /&gt;  }&lt;br /&gt;      &lt;br /&gt;  def solveCramer =&lt;br /&gt;    if (solutionCramer == None)&lt;br /&gt;      "There is no unique solution"&lt;br /&gt;    else&lt;br /&gt;      makeString(getUnknowns(solutionCramer.get))&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-6032759089382990855?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/6032759089382990855/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/07/matrices-5.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/6032759089382990855'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/6032759089382990855'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/07/matrices-5.html' title='Matrices 5b'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-8562464516349828539</id><published>2009-06-30T21:39:00.002-03:00</published><updated>2009-06-30T21:44:31.028-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='matrix'/><category scheme='http://www.blogger.com/atom/ns#' term='beginner'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Matrices 5</title><content type='html'>Our Matix class is now almost complete. There are few methods I intend to add to it, and one I intend to change. Most of this is pretty straight-forward, though, so I’ll be quick about it.&lt;br /&gt;&lt;br /&gt;First, matrix transposition:&lt;br /&gt;&lt;br /&gt;  def transpose = new MatrixInt(createArrays(cols, rows, (row,col) =&gt; this(col,row)))&lt;br /&gt;&lt;br /&gt;Pretty trivial. Next, determinant. To compute the determinant of a matrix, though, I need to compute some co-factors of it. The co-factor method is the only one I’m unhappy about. My original implementation was something like this:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;    for((i: Int) &amp;lt;- (0 until rows).toArray; if i != row)&lt;br /&gt;      yield for((j: Int) &amp;lt;- (0 until cols).toArray; if j != col)&lt;br /&gt;        yield f(i,j)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;That’s a pretty good implemention, but then I went and factored that code out of it and into createArrays. Unfortunately, there is no “if” in createArrays, and I’m not willing to add them for the sake one one method, as this can have some performance impact, and createArrays is used everywhere.&lt;br /&gt;&lt;br /&gt;I could create a “createArraysCond” or something. That would do, but there is only one method that would make use of it. I’m wary of premature refactoring. :-)&lt;br /&gt;&lt;br /&gt;So I ended with the method below. Also, the determinant:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  def cofactor(row: Int, col: Int) = new MatrixInt(createArrays(rows-1, cols-1, (i,j) =&gt;&lt;br /&gt;    this(i + (if (i &amp;lt; row) 0 else 1), j + (if (j &amp;lt; col) 0 else 1))))&lt;br /&gt;&lt;br /&gt;  protected def sign(row: Int, col: Int) = if ((col + row) % 2 == 0) 1 else -1&lt;br /&gt;  &lt;br /&gt;  lazy val determinant: Int =&lt;br /&gt;    if (rows != cols)&lt;br /&gt;      throw new UnsupportedOperationException&lt;br /&gt;    else rows match {&lt;br /&gt;      case 1 =&gt; this(0,0)&lt;br /&gt;      case 2 =&gt; this(0,0)*this(1,1) - this(1,0)*this(0,1)&lt;br /&gt;      case n =&gt; (&lt;br /&gt;        _row(0).zipWithIndex&lt;br /&gt;        map Function.tupled((value, col) =&gt; value * cofactor(0, col).determinant * sign(0, col))&lt;br /&gt;        reduceLeft (_+_)&lt;br /&gt;        )&lt;br /&gt;      }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;I factored out “sign” because it is used in another method, and makes the code much clearer. Since our matrix is immutable, I made determinant “lazy val”. It’s a val because I need compute it only once – it’s value won’t change. It’s lazy because, that way, it won’t get computed until someone actually uses it. Otherwise, all matrices would have their determinant computed at creation time. This way, if you never need the determinant of a matrix, it won’t ever get computed.&lt;br /&gt;&lt;br /&gt;The last methods I want to create for Matrix are “adjugate”, which will compute the adjugate, or adjoint, matrix, and “inverse”, which will compute the inverse of a Matrix. Since we are dealing with integers, computing the inverse will be a bit more difficult than if we were using doubles. Anyway, let’s do it. First, let’s define a “/” operator between matrix and integer. We’ll also define a “%” operator, which is pretty useful when dividing integers.&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  def /(n: Int): MatrixInt = &lt;br /&gt;    new MatrixInt(createArrays(rows, cols, (row, col) =&gt; this(row,col) / n))&lt;br /&gt;&lt;br /&gt;  def %(n: Int): MatrixInt = &lt;br /&gt;    new MatrixInt(createArrays(rows, cols, (row, col) =&gt; this(row,col) % n))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Next, I’ll do the adjugate:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  def minor(row: Int, col: Int) = cofactor(row, col).determinant&lt;br /&gt;  &lt;br /&gt;  lazy val adjugate: MatrixInt = new MatrixInt(createArrays(cols, rows, (row, col) =&gt;&lt;br /&gt;    minor(col, row) * sign(col, row)&lt;br /&gt;  ))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This is a bit confusing because I’m inverting at the same time I’m computing the minors. This saves a transposition step, though.&lt;br /&gt;&lt;br /&gt;Finally, I’ll compute the inverse matrix, after asserting the matrix does have an integer inverse:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  def isDivisibleBy(n: Int): Boolean =&lt;br /&gt;    (this % n).self flatMap (row =&gt; row) forall (_ == 0)&lt;br /&gt;  &lt;br /&gt;  lazy val inverse: Option[MatrixInt] =&lt;br /&gt;    if (determinant == 0 || !isDivisibleBy(determinant))&lt;br /&gt;      None&lt;br /&gt;    else&lt;br /&gt;      Some(adjugate / determinant)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;We finally have something new to look at. In the method isDivisibleBy, we first use the method “flapMap” to unnest the arrays, producing an Array[Int] containing all values of the matrix. Then we use “forall” in that. The method “forall” returns true if, and only if, the function passed to it (“_ == 0”) is true for all elements of the collection on which “forall” was invoked.&lt;br /&gt;&lt;br /&gt;Or, in other words, “forall” will check that (this % n) results in a matrix of zeros.&lt;br /&gt;&lt;br /&gt;The other interesting thing here is the use of Option. If you haven’t seen Option before, you probably haven’t seen much Scala code before. Option is Scala’s way of saying “this is not available”. An Option is a class, with a subclass called “Some”, and a singleton object called “None”. So where, in other languages, you might see a “null” value, in Scala the library will usually return a None instead.&lt;br /&gt;&lt;br /&gt;On the other hand, instead of returning the value you want, it returns Some(value). This way, you need to test to see if the value you want is actually available, and then get it. There are many ways of doing that, and it pays to look up the API for Option.&lt;br /&gt;&lt;br /&gt;The very last thing I’ll do with MatrixInt is change the exponentiation to be able to receive negative values, and we’ll see here one way of getting the value for an Option:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  def **(n: Int): MatrixInt =&lt;br /&gt;    if (rows != cols)&lt;br /&gt;      throw new UnsupportedOperationException&lt;br /&gt;    else n match {&lt;br /&gt;      case 0 =&gt; unitMatrixInt(rows)&lt;br /&gt;      case 1 =&gt; this&lt;br /&gt;      case 2 =&gt; this * this&lt;br /&gt;      case negative if negative &amp;lt; 0 =&gt; &lt;br /&gt;        (this ** negative.abs).inverse getOrElse (throw new UnsupportedOperationException) &lt;br /&gt;      case odd if odd % 2 == 1 =&gt; this ** (odd - 1) * this&lt;br /&gt;      case even =&gt; this ** (even / 2) ** 2&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;We’ll finish this installment with a couple of methods to solve systems of linear equations. It is tempting to create the methods inside MatrixInt itself, but solving linear equations is something you can do using matrices, not a matrix operation in itself.&lt;br /&gt;&lt;br /&gt;I’m not sure what a good abstraction would be. We might just create the functions inside an object, and import them. Instead, I’ll create a small class to do that. First, let’s get a toString method. This method is quick and dirty, and could use some improvements. In particular, we could align the columns, like MatrixInt does, and we could treat negative numbers to avoid showing things like “+ -5”. That, I’ll leave as an exercise! :-)&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;class LinearEquations(val m: MatrixInt, val r: MatrixInt) {&lt;br /&gt;  require(m.rows == r.rows &amp;&amp; r.cols == 1)&lt;br /&gt;  &lt;br /&gt;  override def toString =&lt;br /&gt;    (for (rowNumber &amp;lt;- 0 until m.rows;&lt;br /&gt;          row = m.row(rowNumber).zipWithIndex)&lt;br /&gt;     yield (row &lt;br /&gt;            map Function.tupled(_+"x("+_+")") &lt;br /&gt;            mkString (""," + "," = ")) + r(rowNumber,0))&lt;br /&gt;    .mkString("\n")&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;To this class, we’ll add two solvers. First, through the inverted matrix, which should be pretty easy. We’ll also add a method which prints the equation with the unknowns replaced with the solution, so we can easily verify it by eye:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  lazy val solutionInverse: Option[MatrixInt] =&lt;br /&gt;    if (m.inverse == None)&lt;br /&gt;      None&lt;br /&gt;    else&lt;br /&gt;      Some(m.inverse.get * r) &lt;br /&gt;&lt;br /&gt;  def solveInverse =&lt;br /&gt;    if (solutionInverse == None)&lt;br /&gt;      "There is no unique solution"&lt;br /&gt;    else&lt;br /&gt;      (for (rowNumber &amp;lt;- 0 until m.rows;&lt;br /&gt;            row = m.row(rowNumber).zipWithIndex)&lt;br /&gt;       yield (row &lt;br /&gt;              map Function.tupled((value, col) =&gt; value+"*"+solutionInverse.get(col,0)) &lt;br /&gt;              mkString (""," + "," = ")) + r(rowNumber,0))&lt;br /&gt;      .mkString("\n")&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;We can already see the potential for refactoring. Now, the Cramer’s Rule. This is more difficult, because we need to compute each element of the solution.  Though a bit more complex, it isn’t terribly so:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  lazy val solutionCramer: Option[MatrixInt] = {&lt;br /&gt;    val vector = r.toArray.flatMap(x =&gt; x)&lt;br /&gt;    if (m.determinant == 0)&lt;br /&gt;      None&lt;br /&gt;    else&lt;br /&gt;      Some(MatrixInt(&lt;br /&gt;        for((col: Int) &amp;lt;- (0 until m.cols).toArray)&lt;br /&gt;        yield Array(&lt;br /&gt;            m.replaceCol(col, vector).determinant / m.determinant &lt;br /&gt;          )&lt;br /&gt;      ))&lt;br /&gt;  }&lt;br /&gt;      &lt;br /&gt;  def solveCramer =&lt;br /&gt;    if (solutionCramer == None)&lt;br /&gt;      "There is no unique solution"&lt;br /&gt;    else&lt;br /&gt;      (for (rowNumber &amp;lt;- 0 until m.rows;&lt;br /&gt;            row = m.row(rowNumber).zipWithIndex)&lt;br /&gt;       yield (row &lt;br /&gt;              map Function.tupled((value, col) =&gt; value+"*"+solutionCramer.get(col,0)) &lt;br /&gt;              mkString (""," + "," = ")) + r(rowNumber,0))&lt;br /&gt;      .mkString("\n")&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;More refactoring potential. We’ll finish this installment with an example of LinearEquations in action, followed by the complete source code for what we have done so far.&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; m&lt;br /&gt;res5: Array[Array[Int]] = Array(Array(5, -4), Array(6, -5))&lt;br /&gt;&lt;br /&gt;scala&gt; r&lt;br /&gt;res6: Array[Array[Int]] = Array(Array(2), Array(1))&lt;br /&gt;&lt;br /&gt;scala&gt; new LinearEquations(m, r)&lt;br /&gt;res2: LinearEquations =&lt;br /&gt;5x(0) + -4x(1) = 2&lt;br /&gt;6x(0) + -5x(1) = 1&lt;br /&gt;&lt;br /&gt;scala&gt; res2.solveInverse&lt;br /&gt;res3: java.lang.String =&lt;br /&gt;5*6 + -4*7 = 2&lt;br /&gt;6*6 + -5*7 = 1&lt;br /&gt;&lt;br /&gt;scala&gt; res2.solveCramer&lt;br /&gt;res4: java.lang.String =&lt;br /&gt;5*6 + -4*7 = 2&lt;br /&gt;6*6 + -5*7 = 1&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;And now, the source code:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;package com.blogspot.dcsobral.matrix&lt;br /&gt;&lt;br /&gt;class MatrixInt private (private val self: Array[Array[Int]]) {&lt;br /&gt;  import MatrixInt._&lt;br /&gt;&lt;br /&gt;  val rows = self.size&lt;br /&gt;  val cols = self(0).size&lt;br /&gt;  &lt;br /&gt;  private def _row(n: Int): Array[Int] = self(n)&lt;br /&gt;  private def _col(n: Int): Array[Int] = self map (_(n))&lt;br /&gt;  &lt;br /&gt;  def row(n: Int): Array[Int] = _row(n) map (x =&gt; x)&lt;br /&gt;  def col(n: Int): Array[Int] = _col(n)&lt;br /&gt;&lt;br /&gt;  def apply(i: Int, j: Int): Int =&lt;br /&gt;    if (i &gt;= rows || j &gt;= cols || i &amp;lt; 0 || j &amp;lt; 0)&lt;br /&gt;      throw new IndexOutOfBoundsException&lt;br /&gt;    else&lt;br /&gt;      self(i)(j)&lt;br /&gt;&lt;br /&gt;  def update(row: Int, col: Int, newValue: Int): MatrixInt = &lt;br /&gt;    new MatrixInt(createArrays(rows, cols, (i,j) =&gt;&lt;br /&gt;      if (row == i &amp;&amp; col == j) newValue else this(i,j)))&lt;br /&gt;&lt;br /&gt;  def update(what: Dimension, where: Int, newValue: Array[Int]): MatrixInt =&lt;br /&gt;    what match {&lt;br /&gt;      case Row =&gt; replaceRow(where, newValue)&lt;br /&gt;      case Column =&gt; replaceCol(where, newValue)&lt;br /&gt;    }&lt;br /&gt;      &lt;br /&gt;  def replaceCol(col: Int, newValue: Array[Int]): MatrixInt =&lt;br /&gt;    new MatrixInt(createArrays(rows, cols, (i,j) =&gt;&lt;br /&gt;      if (col == j) newValue(i) else this(i,j)))&lt;br /&gt;&lt;br /&gt;  def replaceRow(row: Int, newValue: Array[Int]): MatrixInt =&lt;br /&gt;    new MatrixInt(createArrays(rows, cols, (i,j) =&gt;&lt;br /&gt;      if (row == i) newValue(j) else this(i,j)))&lt;br /&gt;&lt;br /&gt;  override def equals(other: Any): Boolean = other match {&lt;br /&gt;    case that: MatrixInt =&gt; &lt;br /&gt;      that.canEqual(this) &amp;&amp; self.deepEquals(that.self)&lt;br /&gt;    case _ =&gt; false&lt;br /&gt;  }&lt;br /&gt;  &lt;br /&gt;  def canEqual(other: Any): Boolean = other.isInstanceOf[MatrixInt]&lt;br /&gt;    &lt;br /&gt;  def *(n: Int): MatrixInt = &lt;br /&gt;    new MatrixInt(createArrays(rows, cols, (row, col) =&gt; this(row,col) * n))&lt;br /&gt;&lt;br /&gt;  def /(n: Int): MatrixInt = &lt;br /&gt;    new MatrixInt(createArrays(rows, cols, (row, col) =&gt; this(row,col) / n))&lt;br /&gt;&lt;br /&gt;  def %(n: Int): MatrixInt = &lt;br /&gt;    new MatrixInt(createArrays(rows, cols, (row, col) =&gt; this(row,col) % n))&lt;br /&gt;&lt;br /&gt;  def +(other: MatrixInt): MatrixInt =&lt;br /&gt;    if (rows != other.rows || cols != other.cols)&lt;br /&gt;      throw new IllegalArgumentException&lt;br /&gt;    else&lt;br /&gt;      new MatrixInt(createArrays(rows, cols, (row, col) =&gt; this(row,col) + other(row,col)))&lt;br /&gt;&lt;br /&gt;  def -(other: MatrixInt): MatrixInt =&lt;br /&gt;    if (rows != other.rows || cols != other.cols)&lt;br /&gt;      throw new IllegalArgumentException&lt;br /&gt;    else&lt;br /&gt;      new MatrixInt(createArrays(rows, cols, (row, col) =&gt; this(row,col) - other(row, col)))&lt;br /&gt;&lt;br /&gt;  def *(other: MatrixInt): MatrixInt =&lt;br /&gt;    if (cols != other.rows)&lt;br /&gt;      throw new IllegalArgumentException&lt;br /&gt;    else &lt;br /&gt;      new MatrixInt(createArrays(rows, other.cols, (row, col) =&gt;&lt;br /&gt;        this._row(row) zip other._col(col) map Function.tupled(_*_) reduceLeft (_+_)&lt;br /&gt;      ))&lt;br /&gt;&lt;br /&gt;  def **(n: Int): MatrixInt =&lt;br /&gt;    if (rows != cols)&lt;br /&gt;      throw new UnsupportedOperationException&lt;br /&gt;    else n match {&lt;br /&gt;      case 0 =&gt; unitMatrixInt(rows)&lt;br /&gt;      case 1 =&gt; this&lt;br /&gt;      case 2 =&gt; this * this&lt;br /&gt;      case negative if negative &amp;lt; 0 =&gt; &lt;br /&gt;        (this ** negative.abs).inverse getOrElse (throw new UnsupportedOperationException) &lt;br /&gt;      case odd if odd % 2 == 1 =&gt; this ** (odd - 1) * this&lt;br /&gt;      case even =&gt; this ** (even / 2) ** 2&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;  def toArray = MatrixInt.clone(self)&lt;br /&gt;  &lt;br /&gt;  def transpose = new MatrixInt(createArrays(cols, rows, (row,col) =&gt; this(col,row)))&lt;br /&gt;&lt;br /&gt;  def cofactor(row: Int, col: Int) = new MatrixInt(createArrays(rows-1, cols-1, (i,j) =&gt;&lt;br /&gt;    this(i + (if (i &amp;lt; row) 0 else 1), j + (if (j &amp;lt; col) 0 else 1))))&lt;br /&gt;&lt;br /&gt;  protected def sign(row: Int, col: Int) = if ((col + row) % 2 == 0) 1 else -1&lt;br /&gt;  &lt;br /&gt;  lazy val determinant: Int =&lt;br /&gt;    if (rows != cols)&lt;br /&gt;      throw new UnsupportedOperationException&lt;br /&gt;    else rows match {&lt;br /&gt;      case 1 =&gt; this(0,0)&lt;br /&gt;      case 2 =&gt; this(0,0)*this(1,1) - this(1,0)*this(0,1)&lt;br /&gt;      case n =&gt; (&lt;br /&gt;        _row(0).zipWithIndex&lt;br /&gt;        map Function.tupled((value, col) =&gt; value * cofactor(0, col).determinant * sign(0, col))&lt;br /&gt;        reduceLeft (_+_)&lt;br /&gt;        )&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;  def minor(row: Int, col: Int) = cofactor(row, col).determinant&lt;br /&gt;  &lt;br /&gt;  lazy val adjugate: MatrixInt = new MatrixInt(createArrays(cols, rows, (row, col) =&gt;&lt;br /&gt;    minor(col, row) * sign(col, row)&lt;br /&gt;  ))&lt;br /&gt;&lt;br /&gt;  def isDivisibleBy(n: Int): Boolean =&lt;br /&gt;    (this % n).self flatMap (row =&gt; row) forall (_ == 0)&lt;br /&gt;  &lt;br /&gt;  lazy val inverse: Option[MatrixInt] =&lt;br /&gt;    if (determinant == 0 || !isDivisibleBy(determinant))&lt;br /&gt;      None&lt;br /&gt;    else&lt;br /&gt;      Some(adjugate / determinant)&lt;br /&gt;&lt;br /&gt;  override def toString = {&lt;br /&gt;    val maxNumSize = self.projection flatMap (_ map (_.toString.size)) reduceLeft (_ max _)&lt;br /&gt;    val numFormat = "%"+maxNumSize+"d"&lt;br /&gt;    def formatNumber(n: Int) = numFormat format n&lt;br /&gt;    val top = rows match {&lt;br /&gt;      case 1 =&gt; _row(0) map formatNumber mkString ("&amp;lt; ", " ", " &gt;")&lt;br /&gt;      case _ =&gt; _row(0) map formatNumber mkString ("/ ", " ", " \\") // fix highlighter: "&lt;br /&gt;    }&lt;br /&gt;    val middle = rows match {&lt;br /&gt;      case 1 | 2 =&gt; Nil&lt;br /&gt;      case _ =&gt; self.toList.tail.init map (_ map formatNumber mkString("| "," "," |"))&lt;br /&gt;    }&lt;br /&gt;    val bottom = rows match {&lt;br /&gt;      case 1 =&gt; Nil&lt;br /&gt;      case _ =&gt; List(_row(rows - 1) map formatNumber mkString ("\\ ", " ", " /"))&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    top :: middle ::: bottom mkString "\n"&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;object MatrixInt {&lt;br /&gt;  import MatrixInt._&lt;br /&gt;  implicit def toMatrixInt(m : Array[Array[Int]]) = MatrixInt(m)&lt;br /&gt;&lt;br /&gt;  def apply(array: Array[Array[Int]]): MatrixInt = new MatrixInt(clone(array))&lt;br /&gt;  def apply(rows: Int, cols: Int): MatrixInt = MatrixInt(rows, cols, 0)&lt;br /&gt;  def apply(rows: Int, cols: Int, value: Int): MatrixInt = &lt;br /&gt;    new MatrixInt(createArrays(rows, cols, ((_,_) =&gt; value))) &lt;br /&gt;  def apply(rows: Int, cols: Int, f: (Int,Int) =&gt; Int): MatrixInt = &lt;br /&gt;    new MatrixInt(createArrays(rows, cols, f))&lt;br /&gt;  &lt;br /&gt;  def unitMatrixInt(n: Int) = MatrixInt(n, n, (row,col) =&gt; (if (row == col) 1 else 0)) &lt;br /&gt;&lt;br /&gt;  protected def createArrays(rows: Int, cols: Int, f: (Int, Int) =&gt; Int) =&lt;br /&gt;    for((i: Int) &amp;lt;- (0 until rows).toArray)&lt;br /&gt;      yield for((j: Int) &amp;lt;- (0 until cols).toArray)&lt;br /&gt;        yield f(i,j)&lt;br /&gt;&lt;br /&gt;  protected def clone(a: Array[Array[Int]]) =&lt;br /&gt;    createArrays(a.size, a(0).size, (row, col) =&gt; a(row)(col))&lt;br /&gt;    &lt;br /&gt;  sealed abstract class Dimension&lt;br /&gt;  case object Row extends Dimension&lt;br /&gt;  case object Column extends Dimension&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class LinearEquations(val m: MatrixInt, val r: MatrixInt) {&lt;br /&gt;  require(m.rows == r.rows &amp;&amp; r.cols == 1)&lt;br /&gt;  &lt;br /&gt;  override def toString =&lt;br /&gt;    (for (rowNumber &amp;lt;- 0 until m.rows;&lt;br /&gt;          row = m.row(rowNumber).zipWithIndex)&lt;br /&gt;     yield (row &lt;br /&gt;            map Function.tupled(_+"x("+_+")") &lt;br /&gt;            mkString (""," + "," = ")) + r(rowNumber,0))&lt;br /&gt;    .mkString("\n")&lt;br /&gt;&lt;br /&gt;  lazy val solutionInverse: Option[MatrixInt] =&lt;br /&gt;    if (m.inverse == None)&lt;br /&gt;      None&lt;br /&gt;    else&lt;br /&gt;      Some(m.inverse.get * r) &lt;br /&gt;&lt;br /&gt;  def solveInverse =&lt;br /&gt;    if (solutionInverse == None)&lt;br /&gt;      "There is no unique solution"&lt;br /&gt;    else&lt;br /&gt;      (for (rowNumber &amp;lt;- 0 until m.rows;&lt;br /&gt;            row = m.row(rowNumber).zipWithIndex)&lt;br /&gt;       yield (row &lt;br /&gt;              map Function.tupled((value, col) =&gt; value+"*"+solutionInverse.get(col,0)) &lt;br /&gt;              mkString (""," + "," = ")) + r(rowNumber,0))&lt;br /&gt;      .mkString("\n")&lt;br /&gt;&lt;br /&gt;  lazy val solutionCramer: Option[MatrixInt] = {&lt;br /&gt;    val vector = r.toArray.flatMap(x =&gt; x)&lt;br /&gt;    if (m.determinant == 0)&lt;br /&gt;      None&lt;br /&gt;    else&lt;br /&gt;      Some(MatrixInt(&lt;br /&gt;        for((col: Int) &amp;lt;- (0 until m.cols).toArray)&lt;br /&gt;        yield Array(&lt;br /&gt;            m.replaceCol(col, vector).determinant / m.determinant &lt;br /&gt;          )&lt;br /&gt;      ))&lt;br /&gt;  }&lt;br /&gt;      &lt;br /&gt;  def solveCramer =&lt;br /&gt;    if (solutionCramer == None)&lt;br /&gt;      "There is no unique solution"&lt;br /&gt;    else&lt;br /&gt;      (for (rowNumber &amp;lt;- 0 until m.rows;&lt;br /&gt;            row = m.row(rowNumber).zipWithIndex)&lt;br /&gt;       yield (row &lt;br /&gt;              map Function.tupled((value, col) =&gt; value+"*"+solutionCramer.get(col,0)) &lt;br /&gt;              mkString (""," + "," = ")) + r(rowNumber,0))&lt;br /&gt;      .mkString("\n")&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-8562464516349828539?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/8562464516349828539/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/matrices-5.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8562464516349828539'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8562464516349828539'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/matrices-5.html' title='Matrices 5'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-127487166778612960</id><published>2009-06-28T23:43:00.003-03:00</published><updated>2009-06-29T00:04:02.266-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='matrix'/><category scheme='http://www.blogger.com/atom/ns#' term='beginner'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Matrices 4</title><content type='html'>We have a reasonable Matrix class at this point, but it still has some deficiencies. There are a few common matrix operations we can add to it, and there are some problems related to the usability of the class. Let’s see them.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Equality&lt;br /&gt;&lt;/strong&gt;&lt;br /&gt;If you try “unitMatrixInt(2) == unitMatrixInt(2)”, you’ll get false as result. This happens because we did not provide an “equals” method, and the default “equals” method compares object references. Or, in other words, it tests if the objects are the &lt;em&gt;same&lt;/em&gt;, not if the objects are equal. If that’s still unclear, see the following example:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; unitMatrixInt(2) == unitMatrixInt(2)&lt;br /&gt;res8: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; val a = unitMatrixInt(2)&lt;br /&gt;a: teste.MatrixInt =&lt;br /&gt;/ 1 0 \&lt;br /&gt;\ 0 1 /&lt;br /&gt;&lt;br /&gt;scala&gt; val b = unitMatrixInt(2)&lt;br /&gt;b: teste.MatrixInt =&lt;br /&gt;/ 1 0 \&lt;br /&gt;\ 0 1 /&lt;br /&gt;&lt;br /&gt;scala&gt; val c = a&lt;br /&gt;c: teste.MatrixInt =&lt;br /&gt;/ 1 0 \&lt;br /&gt;\ 0 1 /&lt;br /&gt;&lt;br /&gt;scala&gt; a == a&lt;br /&gt;res9: Boolean = true&lt;br /&gt;&lt;br /&gt;scala&gt; a == b&lt;br /&gt;res10: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; a == c&lt;br /&gt;res11: Boolean = true&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Writing an equals method can be tricky, but I’m not going to discuss here why such a method must be written this or that way, as there are good references on the web. I usually recommend &lt;a href="http://www.artima.com/lejava/articles/equality.html"&gt;this one&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;I &lt;em&gt;will&lt;/em&gt; talk about the syntactical aspect of making such a method. First, though the examples show the method “==”, I keep talking about “equals”. That’s because “==”, as well as “!=”, in Scala is implemented in terms of the “equals” method. So if you want to change them, you implement “equals”.&lt;br /&gt;&lt;br /&gt;Now, it’s not enough just to call it “equals”. It has to have the correct signature, which is to receive a single parameter of type Any, and return a Boolean. The method below will be good enough, with the addition of a canEqual method, and a small change in our class declaration:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;class MatrixInt private (private val self: Array[Array[Int]]) {&lt;br /&gt;...&lt;br /&gt;  override def equals(other: Any): Boolean = other match {&lt;br /&gt;    case that: MatrixInt =&gt;&lt;br /&gt;      that.canEqual(this) &amp;amp;&amp;amp; self.deepEquals(that.self)&lt;br /&gt;    case _ =&gt; false&lt;br /&gt;  }&lt;br /&gt; &lt;br /&gt;  def canEqual(other: Any): Boolean = other.isInstanceOf[MatrixInt]&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;We changed the constructor so that self got declared as a “private val”, otherwise it won’t be visible even to other objects of the same class. We could also get a copy of a MatrixInt’s array representation, and compare against that, but that can make equals quite slow. To get such a copy, though, we would use the “toArray” method, which I thought I had presented in the first installment of these posts, but I now find I didn’t. Let’s correct that oversight:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  def toArray = MatrixInt.clone(self)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;We produce a copy of the array, so that changes to it won’t affect this object. Anyway, now the test works as expected:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; val a = unitMatrixInt(2)&lt;br /&gt;a: teste2.MatrixInt =&lt;br /&gt;/ 1 0 \&lt;br /&gt;\ 0 1 /&lt;br /&gt;&lt;br /&gt;scala&gt; val b = unitMatrixInt(2)&lt;br /&gt;b: teste2.MatrixInt =&lt;br /&gt;/ 1 0 \&lt;br /&gt;\ 0 1 /&lt;br /&gt;&lt;br /&gt;scala&gt; val c = a&lt;br /&gt;c: teste2.MatrixInt =&lt;br /&gt;/ 1 0 \&lt;br /&gt;\ 0 1 /&lt;br /&gt;&lt;br /&gt;scala&gt; a == a&lt;br /&gt;res12: Boolean = true&lt;br /&gt;&lt;br /&gt;scala&gt; a == b&lt;br /&gt;res13: Boolean = true&lt;br /&gt;&lt;br /&gt;scala&gt; a == c&lt;br /&gt;res14: Boolean = true&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Updating &lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;We also want to check to see it returns false for different matrices. To do that, though, we would like to produce a different matrix easily. Unfortunately, we have no way to do that. Well, we can generate unit matrices of different sizes, but if we just wanted to change a small value in one we have, we can do that.&lt;br /&gt;&lt;br /&gt;Since our class is immutable, we do not expect it to actually change to something else, but when we do “1+1”, we do not change “1”, we just produce a new value. We can do the same thing, and enable individual cell changes in our matrix, like this:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  def update(row: Int, col: Int, newValue: Int): MatrixInt =&lt;br /&gt;    new MatrixInt(createArrays(rows, cols, (i,j) =&gt;&lt;br /&gt;      if (row == i &amp;amp;&amp;amp; col == j) newValue else this(i,j)))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Here are some tests, then:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; val a = unitMatrixInt(2)&lt;br /&gt;a: teste3.MatrixInt =&lt;br /&gt;/ 1 0 \&lt;br /&gt;\ 0 1 /&lt;br /&gt;&lt;br /&gt;scala&gt; a == unitMatrixInt(3)&lt;br /&gt;res20: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; a == unitMatrixInt(2)&lt;br /&gt;res21: Boolean = true&lt;br /&gt;&lt;br /&gt;scala&gt; a == (a + a)&lt;br /&gt;res22: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; a == a*2&lt;br /&gt;res23: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; a == a * a // True! 1 == 1 * 1&lt;br /&gt;res24: Boolean = true&lt;br /&gt;&lt;br /&gt;scala&gt; val b = a(1,0) = 1&lt;br /&gt;b: teste3.MatrixInt =&lt;br /&gt;/ 1 0 \&lt;br /&gt;\ 1 1 /&lt;br /&gt;&lt;br /&gt;scala&gt; a&lt;br /&gt;res25: teste3.MatrixInt =&lt;br /&gt;/ 1 0 \&lt;br /&gt;\ 0 1 /&lt;br /&gt;&lt;br /&gt;scala&gt; a == b&lt;br /&gt;res26: Boolean = false&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;So, where’s “update”? It is actually used when declaring “b”. When you write “id(…) = value” in Scala, the compiler translates that to “id.update(…,value)”. So we could have also written this:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; val b = a.update(1,0,1)&lt;br /&gt;b: teste3.MatrixInt =&lt;br /&gt;/ 1 0 \&lt;br /&gt;\ 1 1 /&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Let’s also make it easy to change a whole column or a whole row. We can already do “a.row(0)” or “c.col(1)”, so doing “a.row(0) = …” would be nice. Scala has something similar, in that any method called “field_=” will be called if you write “id.field = …”. Unfortunately, if we try that here it won’t work, because “id.field” is already the name of a method which takes a parameter (the row or column). If it did not take any parameters, it would work. As it is, we’ll just have to make do with something else:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  def replaceCol(col: Int, newValue: Array[Int]): MatrixInt =&lt;br /&gt;    new MatrixInt(createArrays(rows, cols, (i,j) =&gt;&lt;br /&gt;      if (col == j) newValue(i) else this(i,j)))&lt;br /&gt;     &lt;br /&gt;  def replaceRow(row: Int, newValue: Array[Int]): MatrixInt =&lt;br /&gt;    new MatrixInt(createArrays(rows, cols, (i,j) =&gt;&lt;br /&gt;      if (row == i) newValue(j) else this(i,j)))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;And we can use it like this:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; val a = unitMatrixInt(3)&lt;br /&gt;a: teste6.MatrixInt =&lt;br /&gt;/ 1 0 0 \&lt;br /&gt;| 0 1 0 |&lt;br /&gt;\ 0 0 1 /&lt;br /&gt;&lt;br /&gt;scala&gt; a.replaceCol(0, a.col(2))&lt;br /&gt;res39: teste6.MatrixInt =&lt;br /&gt;/ 0 0 0 \&lt;br /&gt;| 0 1 0 |&lt;br /&gt;\ 1 0 1 /&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;There is one alternative, though, which I show below. I’m using the update method, and a symbol to identify what is being updated:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  def update(what: Symbol, where: Int, newValue: Array[Int]): MatrixInt =&lt;br /&gt;    what match {&lt;br /&gt;      case 'row =&gt; replaceRow(where, newValue)&lt;br /&gt;      case 'col | 'column =&gt; replaceCol(where, newValue)&lt;br /&gt;      case _ =&gt; throw new IllegalArgumentException&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;scala&gt; val a = unitMatrixInt(3)&lt;br /&gt;a: teste7.MatrixInt =&lt;br /&gt;/ 1 0 0 \&lt;br /&gt;| 0 1 0 |&lt;br /&gt;\ 0 0 1 /&lt;br /&gt;&lt;br /&gt;scala&gt; a('row, 1) = a.row(0)&lt;br /&gt;res41: teste7.MatrixInt =&lt;br /&gt;/ 1 0 0 \&lt;br /&gt;| 1 0 0 |&lt;br /&gt;\ 0 0 1 /&lt;br /&gt;&lt;br /&gt;scala&gt; a('column, 2) = a.row(0)&lt;br /&gt;res42: teste7.MatrixInt =&lt;br /&gt;/ 1 0 1 \&lt;br /&gt;| 0 1 0 |&lt;br /&gt;\ 0 0 0 /&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Symbols are similar to String. The technical differences aren’t really much important – it’s their intent usage that differs. While strings are made to be shown to a user or received from them, a symbol is a piece of information exchanged between different parts of a program. They are very popular in some languages, but not so much on Scala.&lt;br /&gt;&lt;br /&gt;One reason for their lack of popularity is that you don’t get any compile-time checks using them. If I misspelled “colunm” instead of “column”, the program would compile, and I’d get an exception at run-time – if I was lucky enough to catch it before the user.&lt;br /&gt;&lt;br /&gt;Since we are using a statically typed language, we would like to catch such errors at compile-time. We can do that with Enumerations. Using a Scala enumeration is a bit more complex than other languages, as it’s not built in the language, but a library like anything else. It will provide just the checks we want, though.&lt;br /&gt;&lt;br /&gt;First, we need to declare an object to be our enumeration. We’ll do this in the MatrixInt object-companion. We’ll also declare a type inside the object, to be used in our method declaration. It goes like this:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  object Dimension extends Enumeration {&lt;br /&gt;    type Dimension = Value&lt;br /&gt;    val Row, Column = Value&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;“Value”, here, is both a subclass of Enumeration and a method which will return a new instance of type Value each time it is called. These instances will always be different between them. Note that when you declare “val Row, Column = Value”, Scala converts this into “val Row = Value; val Column = Value”, so “Value” gets invoked twice. If “Value” was called only once, then Row would be equal to Column, which is not something we want.&lt;br /&gt;&lt;br /&gt;We might like to import the contents of the Dimension object inside the class too, so that we can write “what: Dimension” instead of “what: Dimension.Dimension” (or even “what: MatrixInt.Dimension.Dimension”, if we hadn’t imported object MatrixInt’s contents already). Simple line:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  import MatrixInt.Dimension._&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now we can rewrite our method:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  def update(what: Dimension, where: Int, newValue: Array[Int]): MatrixInt =&lt;br /&gt;    what match {&lt;br /&gt;      case Row =&gt; replaceRow(where, newValue)&lt;br /&gt;      case Column =&gt; replaceCol(where, newValue)&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;It’s important that Row and Column were declared capitalized – the first letter is uppercase. If we used “row” and “column”, then the match would simply assign “what” to “row”, like it did to “even” and “odd” in “**”, and execute the first statement. Since we used capitalized identifiers, the case statement compares “what” to the value of Row, as if it was a literal, and assigns nothing.&lt;br /&gt;&lt;br /&gt;Note also that we dropped the default case. One has to be careful, though, because the compiler won’t warn against missing case statements. Here are some usage examples:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; a(Row, 2) = a.row(1)&lt;br /&gt;&amp;lt;console&gt;:13: error: not found: value Row&lt;br /&gt;       a(Row, 2) = a.row(1)&lt;br /&gt;         ^&lt;br /&gt;&lt;br /&gt;scala&gt; a(Dimension.Row, 2) = a.row(1)&lt;br /&gt;res1: teste.MatrixInt =&lt;br /&gt;/ 1 0 0 \&lt;br /&gt;| 0 1 0 |&lt;br /&gt;\ 0 1 0 /&lt;br /&gt;&lt;br /&gt;scala&gt; import Dimension._&lt;br /&gt;import Dimension._&lt;br /&gt;&lt;br /&gt;scala&gt; a(Row, 2) = a.row(1)&lt;br /&gt;res2: teste.MatrixInt =&lt;br /&gt;/ 1 0 0 \&lt;br /&gt;| 0 1 0 |&lt;br /&gt;\ 0 1 0 /&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Can we do something about not getting warnings about missing case statements? As a matter of fact, yes, we can. Let’s rewrite once again our method. This time, we’ll use a case objects. Let’s show it first, and then discuss it. First, we replace the whole Dimension object by this:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  sealed abstract class Dimension&lt;br /&gt;  case object Row extends Dimension&lt;br /&gt;  case object Column extends Dimension&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Since we don’t have any nested declaration, we can do away with the extra import line. As for the rest… the update method doesn’t actually need any changes! The type, Dimension, has been declared. Row and Column are singleton objects, capitalized so that they can be used inside case statements as if they were literals.&lt;br /&gt;&lt;br /&gt;There are two new things here. The “sealed” keyword, and the “case” keyword. Anyone reading about Scala has probably seen case classes. A case class is a class mostly like any other, but with a few methods automatically created by the compiler. A case object is similar to case class, and used instead of them when a case class would not declare any parameter in its constructor.&lt;br /&gt;&lt;br /&gt;The “sealed” keyword means any subclass of “Dimension” must be declared in the same file as it. This way, the compiler can know, without doubt, all subclasses of Dimension, and, thus, perform checks when they get used in match statements. Leave “case Column” out of “update”, and you’ll get this warning:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;MatrixInt.scala:70: warning: match is not exhaustive!&lt;br /&gt;missing combination         Column&lt;br /&gt;&lt;br /&gt;    what match {&lt;br /&gt;    ^&lt;br /&gt;one warning found&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The usage won’t differ much either, and, in fact, won’t require any import beyond the object-companion’s contents:&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; val a = unitMatrixInt(3)&lt;br /&gt;a: teste3.MatrixInt =&lt;br /&gt;/ 1 0 0 \&lt;br /&gt;| 0 1 0 |&lt;br /&gt;\ 0 0 1 /&lt;br /&gt;&lt;br /&gt;scala&gt; a(Row,2) = a.row(0)&lt;br /&gt;res15: teste3.MatrixInt =&lt;br /&gt;/ 1 0 0 \&lt;br /&gt;| 0 1 0 |&lt;br /&gt;\ 1 0 0 /&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;You might wonder, then, why ever use an Enumeration instead of case objects. As a matter of fact, case objects do have advantages many times, such as here. The Enumeration class, though, has many Collection methods, such as elements (iterator on Scala 2.8), which returns an Iterator, map, flatMap, filter, etc.&lt;br /&gt;&lt;br /&gt;We have seen three different ways of implementing our “update” method for rows and columns, each with different characteristics. The very thing that made symbols a bad choice for us – the inability to define what symbols are possible in advance – can be a necessary characteristic in other situations. This goes to the very heart of Scala’s philosophy: do not dictate a solution, but let the programmer find and use the optimal one &lt;em&gt;for his needs&lt;/em&gt;.&lt;br /&gt;&lt;br /&gt;In the next installment we’ll look into computing cofactors, determinants, inverse matrices and then use all that to solve linear equations. I’m afraid there won’t be almost anything new, but, on the positive side, it shouldn’t take long either, and we’ll end up with a reasonable complete Matrix class.&lt;br /&gt;&lt;br /&gt;After that, we’ll look into branching Matrix into other types, and the trade-offs we must make.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-127487166778612960?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/127487166778612960/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/matrices-4.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/127487166778612960'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/127487166778612960'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/matrices-4.html' title='Matrices 4'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-3239010666139499642</id><published>2009-06-26T16:39:00.002-03:00</published><updated>2009-06-26T16:44:47.773-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='agile'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='architecture'/><title type='text'>A Mind is a Terrible Thing to Waste</title><content type='html'>I have just seen a &lt;a href="http://www.infoq.com/presentations/agilists-and-architects"&gt;presentation about Agilists and Architects&lt;/a&gt;, which resonated with an old thought of mine: the waste of experience in the software development process.&lt;br /&gt;&lt;br /&gt;Writing software – programming – is something that takes a huge amount of experience to get right. You have to know the language, of course. You have to know it well enough to avoid getting things wrong because of an unknown feature or characteristic of the language. You have to know the language libraries, frameworks, and development tools. This is the very basic.&lt;br /&gt;&lt;br /&gt;You have to know patterns, and you have to know anti-patterns too. You need experience to realize that a pattern apply to a problem, or that some solution is inching toward an anti-pattern.&lt;br /&gt;&lt;br /&gt;You have to know about security, about protocols, about distributed systems, about parallel systems, about algorithms – of so many types I can’t even list them here.  You have to know about databases, persistence, XML, MVC, DSL, regex, grammars, state machines… we could go on and on. You have to know usability.&lt;br /&gt;&lt;br /&gt;You have to know about programming paradigms. That’s easy, there’s only four or five of them. Or maybe more, depending on who’s definition you are using. And, of course, each paradigm has many variations preferred by one language or another – and who has to deal with a single language these days?&lt;br /&gt;&lt;br /&gt;You have to know computers, and experience here will bring you understanding of performance issues. Experience will also let you identify bugs, or avoid them altogether.&lt;br /&gt;&lt;br /&gt;Then, of course, you have to know CMMI, PMBoK, FPA or any of dozens standards and best practices and processes for software development, quality, testing, team working, etc.&lt;br /&gt;&lt;br /&gt;Finally, of course, you have to know how to communicate with other people, understand the business needs, know the existing systems, the explicit and implicit rules, and, if possible, why it exists in the state it is, why certain decisions were taken, what were the conditions that might change and make it interesting – or even necessary – to take another path, or to avoid certain paths.&lt;br /&gt;&lt;br /&gt;Each of those things you know or don’t have a direct impact on the quality of the code you write. Sure, you can write software with only a small glimpse of all this knowledge, but many times you would have written better, more efficient and more maintainable code if you only knew there was a word to what you were doing. Whole classes might have crumbled to a single library call. You might have avoided code which is intrinsically insecure, protocols which are unfixable. Hell, you might have avoided trying to solve problems known to be unsolvable.&lt;br /&gt;&lt;br /&gt;While deep knowledge is clearly the domain of experts in a field, all those domains come together through the hands of the generalist, who has to know something exists before he can use it.&lt;br /&gt;&lt;br /&gt;So there are architects, who are meant to have all that experience, and lay down the trail for those inexperienced to follow. Only, of course, it doesn’t work that way. The sheer level of detail required in developing software preclude architects from being able to know or influence but a thin, though important, layer of all there is.&lt;br /&gt;&lt;br /&gt;It couldn’t be other way, in truth – if it were possible to write a precise specification of what the software should do, what should be its structure, how it should go about doing what it is supposed to do, well, if it were possible to write such a specification, then we could feed it to the computer and be done with it. In fact, we can write those specifications – they are called “source code”. Source code is not what a computer executes. It’s a specification detailing how to produce the instructions the computer will follow to provide the service required.&lt;br /&gt;&lt;br /&gt;In short, or, rather, in conclusion, programming experience results in code with fewer bugs, that satisfy more completely the users needs, easier to adapt to new needs, and in a shorter time.&lt;br /&gt;&lt;br /&gt;So why the hell does any company even contemplates hiring “junior” programmers? No, let me rephrase that. Why is the average experience of programmers working – coding – for corporations so low? There is an obvious – to me – inversion of value going on there. And looking at companies that make software to be sold as service or at retail – as opposed to producing software to someone else’s specs – I don’t see much disagreement.&lt;br /&gt;&lt;br /&gt;I can see a few reasons why that might be true, of course. First, just because someone acquires experience doesn’t mean he or she &lt;em&gt;learns&lt;/em&gt; new stuff. And the transition from mainframe to personal computing pretty much proved that can be detrimental – when people cling to what they know against the unknown, instead of avoiding what they &lt;em&gt;know&lt;/em&gt; to be wrong, or taking the better one of known alternatives.&lt;br /&gt;&lt;br /&gt;So, corporations “solve” the problem by making experienced people into architects and managers. Being a manager has a quality of its own, and having experience writing software does not really add anything to it. Being an architect takes you too far from where you can make most use of your experience.&lt;br /&gt;&lt;br /&gt;Hopefully, if you are lucky enough to work somewhere software architects have meaningful influence on the software development process, you might get programmers to avoid huge mistakes. And if your corporation is really lucky, you’ll do so without critically impairing the software development process with decisions detached from the reality of the problems being faced.&lt;br /&gt;&lt;br /&gt;I was happy, then, with the ideas presented by Rebecca Parsons and Martin Fowler. It pains me to see so much experience and knowledge wasted because of misguided – or misinformed – processes.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-3239010666139499642?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/3239010666139499642/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/mind-is-terrible-thing-to-waste.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/3239010666139499642'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/3239010666139499642'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/mind-is-terrible-thing-to-waste.html' title='A Mind is a Terrible Thing to Waste'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-4024562365278401842</id><published>2009-06-25T18:57:00.008-03:00</published><updated>2009-09-30T13:17:51.143-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='fibonacci'/><category scheme='http://www.blogger.com/atom/ns#' term='matrix'/><category scheme='http://www.blogger.com/atom/ns#' term='beginner'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Matrices and Fibonacci 3</title><content type='html'>Continuing our series on creating a Matrix class for Scala, now that we have the basics laid down, let’s go back to the Fibonacci problem. We need to do exponentiation of matrices. To do that, we first need to get multiplication going.&lt;br /&gt;&lt;br /&gt;While I have no intention of explaining how to multiply matrices – the web is full of resources if you aren’t familiar with it – it’s important to restate the problem:&lt;br /&gt;&lt;br /&gt;To find element of (row i, column j) of the matrix resulting from AxB, I need to multiply the nth element of row i of matrix A by the nth element of column j of matrix B, for all elements of said row and column, and then add the results. An initial, misguided, attempt might go like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;(for(row &amp;lt;- 0 to rows&lt;br /&gt;     col &amp;lt;- 0 to B.cols&lt;br /&gt;    ) yield A(i,col)*B(row,j)) reduceLeft (_+_)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The problem here is that you are multiplying each element of the row by every element of the column. What we want to do is to “pair” the first element of the row with the first element of the column, the second element of the row with the second of the column, and so forth, and then multiply each pair. This pairing is called “zip” in Scala. You’ll find “zip” – and the occasional variation, such as zipWithIndex – on sequence-like collections, such as List and Array. The zipping thing goes like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;_row(i) zip other._col(j)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;That will create an Array of tuples of Int: Array[Tuple2[Int,Int]], or simply Array[(Int,Int)]. Tuples can be thought of as a small “package” of objects. It’s not a collection – you do not traverse it or iterate through it. Also, each component of it has its own type, as you can see. The only thing you can do with tuples, aside from passing it around, is accessing a tuple’s element. You do this with the methods “_1”, “_2”, “_3”, etc.&lt;br /&gt;&lt;br /&gt;Next, we need to do _1*_2 for each element of that array. You can’t do "map (_._1 * _._2)", as this translates into "map ((x1, x2) =&gt; x1._1 * x2._2)", but map only passes a single argument: the tuple. You can do this, then: "map (t =&gt; t._1 * t._2)". You can, but I won’t… Instead, I’ll pass "(_*_)", an anonymous function that takes two parameters and return the result of their multiplication, to a factory of functions.&lt;br /&gt;&lt;br /&gt;Factories, as anyone familiar with OOP might know, are methods which create new instances of objects. So, what that has to do with a function? Well, a function in Scala is an object that implements the method “apply”. You might wonder if MatrixInt isn’t a function, then, as it implements apply itself. In fact, it could be one, if we chose to extend MatrixInt with the trait Function2 (two arguments to apply).&lt;br /&gt;&lt;br /&gt;At any rate, we’ll use a function factory to produce a new instance of a function, based on (_*_). This factory, called Function.tupled (method “tupled” on singleton object Function), takes a function which receives multiple parameters, and converts it into a function which receives a single tuple instead. After that, we can apply the reduceLeft. Our computation, then, will go like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;this._row(i) zip other._col(j) map Function.tupled(_*_) reduceLeft (_+_)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The method, then, is thus defined:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  def *(other: MatrixInt): MatrixInt =&lt;br /&gt;    if (cols != other.rows)&lt;br /&gt;      throw new IllegalArgumentException&lt;br /&gt;    else&lt;br /&gt;      new MatrixInt(createArrays(rows, other.cols, (row, col) =&gt; {&lt;br /&gt;        this._row(row) zip other._col(col) map Function.tupled(_*_) reduceLeft (_+_)&lt;br /&gt;      }))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;If we do away with the check to see if the matrices are compatible in size, and make allowance for the verbosity of the identifiers being used (like row and col instead of I and j), it comes down to a one-liner. Truly:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala; wrap-lines: false"&gt;&lt;br /&gt;def *(o: MatrixInt) = new MatrixInt(createArrays(rows, o.cols, (i,j) =&gt; _row(i) zip o._col(j) map Function.tupled(_*_) reduceLeft (_+_)))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The only thing left to do is exponentiation. We could do it as a one-liner too:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;def ^(n: Int) = (0 until n).foldLeft(unitMatrixInt(rows))((acc,_) =&gt; acc*this)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The method foldLeft is similar to reduce. But where reduce can be thought of as (((a+b)+c)+d)+e, foldLeft is more like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;var acc = ?&lt;br /&gt;acc = op(acc,a)&lt;br /&gt;acc = op(acc,b)&lt;br /&gt;acc = op(acc,c)&lt;br /&gt;acc = op(acc,d)&lt;br /&gt;acc = op(acc,e)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The most important difference between foldLeft and reduceLeft is that the result of foldLeft, and its accumulator, might be of a different type than the elements the operation is applied upon. With reduceLeft, once you applied acc = op(a,b), if acc where of a different type, then op(acc,c) would be a different method. It might work with some implicits or subtypes, but not for entirely different types.&lt;br /&gt;&lt;br /&gt;Now, I’m not using the range for nothing, except counting the number of times I want to multiply the matrix. Acc is initialized with “unitMatrixInt(rows)”, which would be a method producing a “unit” matrix of the appropriate size. The “1” of matrices. Then I keep multiplying “this” against this accumulator.&lt;br /&gt;&lt;br /&gt;I could create a list of copies of “this”, and then multiply them with reduceLeft too. It would go like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;def **(n: Int) = List.fill(n)(this) reduceLeft (_*_)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Much simpler, but I wanted to mention foldLeft somehow. :-)&lt;br /&gt;&lt;br /&gt;While simplicity has its merits, there is a simple optimization when doing exponentiation by taking advantage of common factors. I went for it in my final implementation:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  def **(n: Int): MatrixInt =&lt;br /&gt;    if (rows != cols  n &lt; 0 =""&gt; unitMatrixInt(rows)&lt;br /&gt;      case 1 =&gt; this&lt;br /&gt;      case 2 =&gt; this * this&lt;br /&gt;      case odd if odd % 2 == 1 =&gt; this ** (odd - 1) * this&lt;br /&gt;      case even =&gt; this ** (even / 2) ** 2&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I'll make a note on the method name, here. I chose ** as this is one of the common names for such an operation on computer languages. Another, less common, name is ^. I prefer the later, but it has a very low precedence. In fact, this very method would be broken as written, because "(odd - 1) * this" would have precedence over "this ** (odd - 1)", which would completely invert the logic and cause a compilation error.&lt;br /&gt;&lt;br /&gt;Now, aside from , ^, &amp;amp;, &lt;&gt;, = and !, :, +, -, * and / and % (ordered by precedence, by the way), all other special characters have a higher precedence. If I called it "@", for instance, then "a * b @ c" would behave as one would expect it too. Unfortunately, no one would expect "@" to be an exponentiation character. But if I were to make extensive use of this library in formulas and expressions, I might well go for something like that, to prevent unexpected errors due to precedence.&lt;br /&gt;&lt;br /&gt;Anyway, we need to define unitMatrixInt too. We’ll do so in a companion object. This way, users of this package can create unix matrices if they want to. To create this method, we’ll need a more general factory method, though. We already have most of what we need in createArrays.&lt;br /&gt;&lt;br /&gt;But before I get into that, I want to revise my class definition. Presently, this is what we have:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;class MatrixInt(array: Array[Array[Int]]) {&lt;br /&gt;  private val self = clone(array)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I receive a matrix, and then replicate it internally, so I can be sure it won’t be changed outside my class – and I take care of not changing it inside. But there is a downside to it: “array” continues to be part of my object (see footnote 1)! It becomes a private reference inside my object, and this has some unfortunate consequences. For one thing, since each instance of my class makes reference to the arrays used to build them, those arrays never get deallocated. Now think about all references to “new MatrixInt” inside the class. I use that for every operator. That means I keep TWO copies of a MatrixInt’s array in memory, even when the copy used for construction gets immediately discarded.&lt;br /&gt;&lt;br /&gt;This presents a conundrum.On one hand, if the instances of my class are immutable, then I need the full array to begin with. On the other hand, if I receive an array from an external source, I need to copy it before using, as the original array might get changed by whoever passed it to me.&lt;br /&gt;&lt;br /&gt;We solve this with the help of a private constructor and an object companion. A private constructor is, of course, a constructor that cannot be accessed from outside the class. The private constructor thing is easy:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;class MatrixInt private (array: Array[Array[Int]]) {&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now, how to access it? We cannot define another constructor inside MatrixInt with the same signature – receiving an array of array of Int as parameter – because it would conflict with the first. What we do, then, is use an object companion.&lt;br /&gt;&lt;br /&gt;Simply put, an object companion is a singleton object – declared with the “object” keyword – which has the same name as a class. That grants both the object and the class visibility of each other’s private definitions.&lt;br /&gt;&lt;br /&gt;We’ll then define an “apply” method in that object companion. As you may remember, the “apply” method receives special treatment from the Scala compiler, which enables you to do away with the name – apply – and just pass the parameters to the instance of your object. Since we have to call our object companion “MatrixInt”, then MatrixInt(…) will be converted by Scala into MatrixInt.apply(…). It looks like the instantiation of a new object, only it lacks the “new” keyword.&lt;br /&gt;&lt;br /&gt;Let’s define it, then. First, let’s remove the “val self” from the class, and just receive it in its private constructor. As that constructor will only be accessed through MatrixInt’s object companion, that will be safe.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;class MatrixInt private (self: Array[Array[Int]]) {&lt;br /&gt;  import MatrixInt._&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The import statement makes it possible to access the methods of the object companion without preceding them with “MatrixInt.”. Being a companion object makes the private methods accessible, but does not bring them into scope automatically.&lt;br /&gt;&lt;br /&gt;Now, for the object companion, let’s create it, the factory for MatrixInt, and a couple of helpful factories. We’ll also transfer the “clone” and “createArrays” methods to it, as this method does not make reference to a MatrixInt’s own data, so it doesn’t need to be part of each instance. The definition of toArray needs “MatrixInt.” prepended to “clone” to avoid an ambiguous reference, but nothing else should change.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;object MatrixInt {&lt;br /&gt;  import MatrixInt._&lt;br /&gt;  implicit def toMatrixInt(m : Array[Array[Int]]) = MatrixInt(m)&lt;br /&gt;&lt;br /&gt;  def apply(array: Array[Array[Int]]): MatrixInt = new MatrixInt(clone(array))&lt;br /&gt;  def apply(rows: Int, cols: Int): MatrixInt = MatrixInt(rows, cols, 0)&lt;br /&gt;  def apply(rows: Int, cols: Int, value: Int): MatrixInt =&lt;br /&gt;    new MatrixInt(createArrays(rows, cols, ((_,_) =&gt; value)))&lt;br /&gt;  def apply(rows: Int, cols: Int, f: (Int,Int) =&gt; Int): MatrixInt =&lt;br /&gt;    new MatrixInt(createArrays(rows, cols, f))&lt;br /&gt; &lt;br /&gt;  def unitMatrixInt(n: Int) = MatrixInt(n, n, (row,col) =&gt; (if (row == col) 1 else 0))&lt;br /&gt;&lt;br /&gt;  protected def createArrays(rows: Int, cols: Int, f: (Int, Int) =&gt; Int) =&lt;br /&gt;    for((i: Int) &lt;- (0 until rows).toArray)       yield for((j: Int) &lt;- (0 until cols).toArray)         yield f(i,j)    protected def clone(a: Array[Array[Int]]) =     createArrays(a.size, a(0).size, (row, col) =&gt; a(row)(col))&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;We can now create a MatrixInt by using MatrixInt(Array(Array(…))), but we didn’t – and won’t – change that in the class. The companion object factory produces a clone of the array, just as we wanted. But the arrays produced by MatrixInt’s methods don’t get exposed, so there is no risk in using them. So, by keep using the private constructor inside MatrixInt itself, we prevent unnecessary copies of the arrays produced by each of MatrixInt’s operators.&lt;br /&gt;&lt;br /&gt;We’ll finish today with Fibonacci, but we’ll continue later on. I’ll add some methods for completeness to MatrixInt, and then look into MatrixDouble and solve some linear equations with it.&lt;br /&gt;&lt;br /&gt;After that, we’ll briefly explore ways to make our Matrix class parametrizable, though I’m still in doubt about performance. Still, I’m reading the comments, and I plan to address them one way or another in these posts.&lt;br /&gt;&lt;br /&gt;So, the Fibonacci!&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;def fibonacci(n: Int) = (MatrixInt(Array(Array(1,1),Array(1,0))) ** n)(1,0)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Footnote 1:&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;A &lt;a href="http://www.blogger.com/profile/14790016927189184209"&gt;reader&lt;/a&gt; has brought to my attention that, actually, "array" is not being preserved. I haven't found in Scala specification anything about this, so I'm putting it down to optimization. But because it is not explicitly documented, I advise against taking advantage of it.&lt;br /&gt;&lt;br /&gt;Do note, please, that if you declare "array" to be protected, val or var, or if any method makes use of it, then it will be preserved in the object.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-4024562365278401842?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/4024562365278401842/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/matrices-and-fibonacci-3.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/4024562365278401842'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/4024562365278401842'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/matrices-and-fibonacci-3.html' title='Matrices and Fibonacci 3'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-6407287020583456785</id><published>2009-06-24T19:44:00.005-03:00</published><updated>2009-09-30T18:59:49.128-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='matrix'/><category scheme='http://www.blogger.com/atom/ns#' term='language'/><category scheme='http://www.blogger.com/atom/ns#' term='beginner'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Matrices 2</title><content type='html'>I’ll continue today with a little series for beginners. On my first post I forgot something important. One of the very first things I do with a class is create a toString method. This way, I get instant feedback on how my class is doing, as I paste it into the REPL, and try out the methods I defined.&lt;br /&gt;&lt;br /&gt;So, let’s think of a toString method. Since all data in my class is stored in the private val “self”, we could simply delegate the task of producing a string:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;override def toString = self.toString&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;That might do at first, but it would be unreasonable to expect something better formatted than that. First, let’s see if we can’t get the output in multiple lines, using mkString:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;override def toString = self mkString “\n”&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Unfortunately, the output of that looks like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;res6: String =&lt;br /&gt;[I@196a753&lt;br /&gt;[I@1c36f46&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This wouldn’t happen with a List, but an Array is implemented to be compatible with Java, and Java had Arrays have some intrinsic limitations, as they were present in the language from the very beginning, much before generics, and some design decisions about them proved to be unfortunate. Anyway, let’s fix that:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;override def toString = self map (_ mkString “ “) mkString “\n”&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Better, but we can improve on that still. For one thing, it would be much better if the columns were aligned. Now, to align the columns, we first must know how big a column can get. Or, in other words, we must know the size of the number with the biggest string representation in the matrix.&lt;br /&gt;&lt;br /&gt;So, summing it up, we have to look through all of the matrix elements, get their sizes, and choose the biggest one. Getting a number’s size is easy: number.toString.size. Now, if we had a list, this would be easy, but we have an array of arrays. When we have nested collections and we want to unnest them, we use flatMap. For instance:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; Array(Array(15,0),Array(2,-30)) flatMap (x =&gt; x)&lt;br /&gt;res19: Array[Int] = Array(15, 0, 2, -30)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The flatMap operation we used, (x =&gt; x), simply returns what it was given. If all you want is unnest the collections, this suffices. But, actually, we want the number sizes. Since “x” is an Array, not a number, we can’t do flatMap (x =&gt; x.toString.size). But we can replace the numbers with their sizes, and then unnest the arrays, like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; Array(Array(15,0),Array(2,-30)) flatMap (_ map (_.toString.size))&lt;br /&gt;res20: Array[Int] = Array(2, 1, 1, 3)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Next, we want to get the biggest one. We have a collection of number sizes, and we want to reduce it to the single biggest one. We have two such methods in Scala: reduceLeft and reduceRight. Since “max” is commutative, both will produce the same result. But reduceLeft has a better performance, as it iterates over the collection in the order given. The final code should look like this, then:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;val maxNumSize = self flatMap (_ map (_.toString.size)) reduceLeft (_ max _)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Pretty easy, eh? My first version had three lines, and was much more confusing to read. It helps stating what your problem is – you’ll often see you can do exactly that in Scala. So, we have a size, what do we do with it? Well, let’s just make sure all numbers are printed to that size. If we format them with “%2d”, for instance, every number will take at least two characters, with the left side being filled with a space as needed. To produce such formatted numbers, we’ll make use of RichString’s “format” method:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;override def toString = {&lt;br /&gt; val maxNumSize = self.projection flatMap (_ map (_.toString.size)) reduceLeft (_ max _)&lt;br /&gt; val numFormat = "%"+maxNumSize+"d"&lt;br /&gt; self map (_ map (numFormat format _) mkString “ “) mkString “\n”&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;That’s it! I added a “projection” there to make it a bit more performatic, as it doesn’t produce intermediate arrays. On Scala 2.8, that method gets replaced with “view”, with “projection” remaining as deprecated. Well, that was so easy I want to do more. First, I want to produce little vertical bars on the sides, to make clear the matrix boundaries, in case we are printing them side by side. That just requires changing the inner mkString to mkString(“| “, “ “, “ |”). But I also want to bend the bars up and down, to indicate the top and bottom lines, as well as produce something special for one-line matrices.&lt;br /&gt;&lt;br /&gt;For all of them, we are just making small changes in the inner mkString. We have one for the top line, one for the intermediate ones, and one for the bottom line. We could make a list of all these lines, and then use mkString on the list, but we have to be careful, because the “bottom” line and the “intermediate” lines might not exist, and the top line has two different formats depending on whether the matrix has more than one line or not. Taking that into account, here is a much larger, but, hopefully, nicer toString method:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt; override def toString = {&lt;br /&gt;   val maxNumSize = self.projection flatMap (_ map (_.toString.size)) reduceLeft (_ max _)&lt;br /&gt;   val numFormat = "%"+maxNumSize+"d"&lt;br /&gt;   def formatNumber(n: Int) = numFormat format n&lt;br /&gt;   val top = rows match {&lt;br /&gt;     case 1 =&gt; _row(0) map formatNumber mkString ("&lt; ", " ", " &gt;")&lt;br /&gt;     case _ =&gt; _row(0) map formatNumber mkString ("/ ", " ", " \\")&lt;br /&gt;   }&lt;br /&gt;   val middle = rows match {&lt;br /&gt;     case 1 | 2 =&gt; Nil&lt;br /&gt;     case _ =&gt; self.toList.tail.init map (_ map formatNumber mkString("| "," "," |"))&lt;br /&gt;   }&lt;br /&gt;   val bottom = rows match {&lt;br /&gt;     case 1 =&gt; Nil&lt;br /&gt;     case _ =&gt; List(_row(rows - 1) map formatNumber mkString ("\\ ", " ", " /"))&lt;br /&gt;   }&lt;br /&gt;  &lt;br /&gt;   top :: middle ::: bottom mkString "\n"&lt;br /&gt; }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;In a parting note, someone suggested one technique to be able to parametrize the class. There are many, but they are slower than using "AnyVal" types directly. If I happen to be mistaken, please do post about it at length!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-6407287020583456785?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/6407287020583456785/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/matrices-2.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/6407287020583456785'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/6407287020583456785'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/matrices-2.html' title='Matrices 2'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-8712469125108322765</id><published>2009-06-23T20:00:00.006-03:00</published><updated>2009-06-24T19:54:17.890-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='fibonacci'/><category scheme='http://www.blogger.com/atom/ns#' term='matrix'/><category scheme='http://www.blogger.com/atom/ns#' term='language'/><category scheme='http://www.blogger.com/atom/ns#' term='beginner'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Matrices and Fibonacci 1</title><content type='html'>When I was beginning to learn Scala, I decided one of my projects would be rewrite &lt;a href="http://github.com/raganwald/homoiconic/blob/master/2008-12-17/another_fibonacci.md"&gt;this stuff&lt;/a&gt; in Scala. The idea behind that is to compute &lt;a href="http://en.wikipedia.org/wiki/Fibonacci_number"&gt;Fibonacci Numbers&lt;/a&gt; using matrices. I won’t bother describing how it is done, as this is well covered on both of those links. Suffice to say that I need to computer the nth power of a 2x2 matrix of integers. This project was all but forgotten for a long time…&lt;br /&gt;&lt;br /&gt;So it happened that just yesterday I was cleaning my to-do list, and I came upon that. I took a second look into it, and decided to take the plunge. Now, Raganwald uses an optimization which enables him to do the operations on vectors, but, by now, I actually thought the whole exercise was trivial and pointless.&lt;br /&gt;&lt;br /&gt;I took a brief look into matrix libraries for Scala. I found the &lt;a href="http://code.google.com/p/scalala/"&gt;Scalala&lt;/a&gt; (as in Scala Linear Algebra) library, which does everything I need, very efficiently at that. My problem would be reduced to something like this (untested):&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;def fib(n) = n match {&lt;br /&gt;  case 0 =&gt; throw new IllegalArgumentException&lt;br /&gt;  case 1 =&gt; 1&lt;br /&gt;  case _ =&gt;&lt;br /&gt;    val m = DenseMatrix(2,2)(1); m(1,1) = 0&lt;br /&gt;    val mPowered = m :^ n&lt;br /&gt;    mPowered(0,1)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Boring, wasn’t it? Yeah, I thought so too. Instead, I decided to write my own Matrix library. Pretty trivial stuff, but at least I’d take something out of it, I thought. So, I’ll talk about that: writing my Matrix library. If that will bore you, you might as well stop right here. I’ll show, though, some of the design decisions and constrains I faced. For someone new to Scala, it might be interesting read.&lt;br /&gt;&lt;br /&gt;Well, then, where to start? With a class, of course. Ideally, I’d like to write something like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;class Matrix[T]&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This way, I could use matrices of Double for most use cases, of Ints or Longs for things like the Fibonacci problem, and BigDecimal for tough stuff. Unfortunately, we can’t do that. We need access to operators such as +, - and * over type T, and that means I need an upper bound for T defining these operators. Unfortunately, these types do not share an interface defining those elements. You see, they are not really “classes” as far as Java is concerned, and not being a proper class, they can’t share an abstract class or interface with these methods. Well, BigDecimal is a class, alright, but that’s it.&lt;br /&gt;&lt;br /&gt;Because of this, I decided, instead, to define my class as MatrixInt. This was enough for Fibonacci, but later I created a MatrixDouble as well, just to finish implementing the most basic methods such a class would need.&lt;br /&gt;&lt;br /&gt;There is a way around that. I can get away with a structural type, but that would be so slow as to defeat the whole purpose of a Matrix class. So I’ll skip it altogether.&lt;br /&gt;&lt;br /&gt;The next design decision is how to store my data, and what constructor to use. Generally speaking, there are two strategies for storing a matrix: as a dense matrix or as a sparse matrix. A dense matrix is simply stored as an addressable, fixed-size, contiguously allocated buffer. Or, in other words, an array. A sparse matrix is used for matrices that are very large in their dimensions, but are mostly populated with zeros. Performance can go either way, depending on what kind of data and algorithms you are using those matrices for. For Fibonacci, dense is the way to go. Since it is also the easier way to go, I chose that way.&lt;br /&gt;&lt;br /&gt;We also need to know how many dimensions the matrices may have. For simplicity sake, I chose bi-dimensional matrices, and that’s it. With all that in mind, my class thus began:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;class MatrixInt(array: Array[Array[Int]]) {&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I decided to take an array of proper dimensions as my constructor, instead of providing something special myself. With Scala 2.8, you can pass Array.ofDim(2,2) and be done with it. We’ll see something similar further down too.&lt;br /&gt;&lt;br /&gt;Now, one important thing to consider is that an Array is a mutable object. I have decided to make my matrices immutable, so that I could use them just like I use Ints or Doubles. But, to ensure that is true, I can’t really on the array passed with the constructor, as it might change. So, first thing I do is copy it. Here:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  private def clone(a: Array[Array[Int]]) =&lt;br /&gt;    for((i: Int) &lt;- (0 until a.size).toArray)&lt;br /&gt;      yield for((j: Int) &lt;- (0 until a(0).size).toArray)&lt;br /&gt;        yield a(i)(j)&lt;br /&gt;&lt;br /&gt;  private val self = clone(array)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This clone array method will help in places other than the constructor. For instance, if the user wants the Array representation of the matrix, I have to clone my internal representation before passing it on. But there are more interesting things about it. Let’s consider it…&lt;br /&gt;&lt;br /&gt;One thing to notice about it, is that instead of having a single for/yield statement, I have two, the second being fed to the first’s yield. It is built this way because I want to create an Array of Arrays. Each yield will result in one collection. Two collections, two yield statements.&lt;br /&gt;&lt;br /&gt;Then we have ranges: (0 until a.size) and (0 until a(0).size). A statement like (0 until 5) will produce a range which, when iterated over, will yield 0, 1, 2, 3 and 4. It can do a few other things too, but let’s not be bothered by them. Note that if you want an “inclusive”, range, one which will include the upper limit (5, in the example), you use “to” instead of “until”. Or you create a new range from the existing one with “inclusive”.&lt;br /&gt;&lt;br /&gt;Next, “.toArray”. Though a range will do as far as generating indices, I want yield to return an Array. If you want yield to return collection X, pass a collection X to the for statement. Therefore, “.toArray” to convert the range into an array.&lt;br /&gt;&lt;br /&gt;The final thing to consider is the last yield statement. Yield a(i)(j). As I started writing my methods, I got very similar patterns, with only the last yield changing. So I started to consider how to reuse that code. The thing to consider, here, is that the intent of this double for/yield pattern is to create an array of arrays of the proper size, and populate it with a function of my choosing. Thinking about it that way, a refactoring might be done as follow:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  protected def createArrays(rows: Int, cols: Int, f: (Int, Int) =&gt; Int) =&lt;br /&gt;    for((i: Int) &lt;- (0 until rows).toArray)&lt;br /&gt;      yield for((j: Int) &lt;- (0 until cols).toArray)&lt;br /&gt;        yield f(i,j)&lt;br /&gt;&lt;br /&gt;  protected def clone(a: Array[Array[Int]]) =&lt;br /&gt;    createArrays(a.size, a(0).size, (row, col) =&gt; a(row)(col))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Here I changed from private to protected, as I decided if I ever subclassed it, there would be no point in hiding these methods. I do not publish them, though, because they are helper methods, instead of methods acting upon the object itself.&lt;br /&gt;&lt;br /&gt;Next, a.size and a(0).size were a bit cryptic, weren’t they? When we work on the matrices algorithms, it would be preferable to call them by what they are:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  val rows = array.size&lt;br /&gt;  val cols = array(0).size&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;We would also like to be able to get a particular row or a particular column. It seems getting a particular row would be easy. Just return the subarray:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  def row(n : Int): Array[Int] = self(n)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;There is a serious problem with that, though. I’m returning a mutable object from my own internal data! We could solve that with clone, but clone only worked for bi-dimensional arrays. Well, before we create  new clone, let’s consider a simpler alternative:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  private def _row(n: Int): Array[Int] = self(n)&lt;br /&gt;  def row(n: Int): Array[Int] = _row(n) map (x =&gt; x)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The private definition is here so we can avoid creating new arrays unnecessarily. Internally, we’ll make sure we never change the value of our arrays. The public method creates a new array by the magic of “map”. The method “map” is, in fact, used when you do a for/yield, along with flatMap when the for/yield has multiple iterators. So, in fact, the createArrays method is actually implemented as using map.&lt;br /&gt;&lt;br /&gt;A map will take a collection and produce a new collection with a given mapping. In this case, our mapping is (x =&gt; x), or, in other words, given x, return x, producing a copy of that array. We define cols in a likewise fashion:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  private def _col(n: Int): Array[Int] = self map (_(n))&lt;br /&gt;  def col(n: Int): Array[Int] = _col(n)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;In this case, the private definition and the public definition are the same. Still, I decided to keep a private definition so that I could use _row and _col throughout my class. We’ll also define a method to access a particular element of our matrix:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  def apply(i: Int, j: Int): Int =&lt;br /&gt;    if (i &gt;= rows || j &gt;= cols || i &lt; 0 || j &lt; 0)&lt;br /&gt;      throw new IndexOutOfBoundsException&lt;br /&gt;    else&lt;br /&gt;      self(i)(j)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The method “apply” has a special meaning in Scala, as the compiler translates object(parms) into object.apply(parms). This means that I will be able to access a particular element of a matrix m with “m(i,j)”. Of course, because a matrix has bounds, I must test for them, and throw an appropriate exception if need be.&lt;br /&gt;&lt;br /&gt;Note that I do not declare an @throws annotation, though I might if I wished to. Also, note that I’m returning the result of the if/else expression, and its type should be Int. But in the if statement, I’m throwing an exception, so what gives?&lt;br /&gt;&lt;br /&gt;As it happens, throwing an exception has type Nothing, which is subtype to everything. I’m not sure if the compiler actually assigns a type to “throw”, as this is a keyword. But if I used Scala’s library “error” function instead, the question of the type would be important. For methods and functions which never return, such as error, declaring its type to be Nothing makes it possible to make use of them inside statements whose return type is important.&lt;br /&gt;&lt;br /&gt;We’ll stop today with just three more definitions. Let’s multiply a matrix by an integer, producing a new matrix, as well as add and subtract two arrays. Here is how:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;  def *(n: Int): MatrixInt = &lt;br /&gt;    new MatrixInt(createArrays(rows, cols, (row, col) =&gt; this(row,col) * n))&lt;br /&gt;&lt;br /&gt;  def +(other: MatrixInt): MatrixInt =&lt;br /&gt;    if (rows != other.rows || cols != other.cols)&lt;br /&gt;      throw new IllegalArgumentException&lt;br /&gt;    else&lt;br /&gt;      new MatrixInt(createArrays(rows, cols, (row, col) =&gt; this(row,col) + other(row,col)))&lt;br /&gt;&lt;br /&gt;  def -(other: MatrixInt): MatrixInt =&lt;br /&gt;    if (rows != other.rows || cols != other.cols)&lt;br /&gt;      throw new IllegalArgumentException&lt;br /&gt;    else&lt;br /&gt;      new MatrixInt(createArrays(rows, cols, (row, col) =&gt; this(row,col) - other(row, col)))&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-8712469125108322765?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/8712469125108322765/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/matrices-and-fibonacci-1.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8712469125108322765'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8712469125108322765'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/matrices-and-fibonacci-1.html' title='Matrices and Fibonacci 1'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-8949110097206001488</id><published>2009-06-22T15:44:00.008-03:00</published><updated>2009-06-23T20:18:33.078-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Catching Exceptions</title><content type='html'>A fellow blogger was complaining about Google Code returning an exception instead of null, which made his code look ugly. Not so, says I! Scala (and monads, I suppose) come to rescue:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;def exceptionToLeft[T](f: =&gt; T): Either[java.lang.Throwable, T] = try {&lt;br /&gt;  Right(f)&lt;br /&gt;} catch {&lt;br /&gt;  case ex =&gt; Left(ex)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;exceptionToLeft(obj.methodWhichMightThrow()) match {&lt;br /&gt;  case Right(x) =&gt; // do stuff with x&lt;br /&gt;  case Left(ex) =&gt; println("Oops, got exception " + ex.toString)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Enjoy!&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Update:&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;Scala 2.8 has library help for this, at scala.util.control.Exception. It does require one to specify the exception or exceptions to be caught, which is a good thing, and it has many more usage modes. You can just ignore the exception for computations returning Unit, you can get the result as Some(T) and transform the exceptions in None, etc.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-8949110097206001488?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/8949110097206001488/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/catching-exceptions.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8949110097206001488'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8949110097206001488'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/catching-exceptions.html' title='Catching Exceptions'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-8787276356701388253</id><published>2009-06-18T00:08:00.003-03:00</published><updated>2009-06-18T00:10:04.582-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='equality'/><category scheme='http://www.blogger.com/atom/ns#' term='language'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Equality &amp; Scala 3</title><content type='html'>This one is a quickie. I forgot -- again -- to mention that Scala &lt;i&gt;does&lt;/i&gt; provide a way around having to define your own equals method. To be more specific, case classes come with reasonably defined equals methods.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-8787276356701388253?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/8787276356701388253/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/equality-scala-3.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8787276356701388253'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8787276356701388253'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/equality-scala-3.html' title='Equality &amp; Scala 3'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-5617084856304621087</id><published>2009-06-17T22:11:00.010-03:00</published><updated>2009-06-17T23:50:01.413-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='equality'/><category scheme='http://www.blogger.com/atom/ns#' term='language'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Equality &amp; Scala 2</title><content type='html'>&lt;div&gt;My efforts, yesterday, to come up with an Equatable trait that could ease a bit the knowledge and sheer drudgery of making a valid “equals” method met with unexpected difficulties. While tempted to replace the incorrect code with a correct one before the article got many hits, I decided that the problems I encountered and the mistakes I made taught a lesson by itself.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Anyway, I'd like first to make a few remarks that were missing from that post. One thing to notice here is that while this trait might be useful to some people, it is slower than a well thought-out equals definition. What I'm trying to do is see how much Scala let me make the job of creating valid equals methods both easier and safer.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;It all comes down to the idea that, being equality in languages with subclassing so full of pitfalls, and the &lt;em&gt;general&lt;/em&gt; solution to it being a well-defined pattern, those languages ought to be doing something about it at the language level. Or library level, if possible.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;It does cross my mind that this problem might be much more efficiently and elegantly solved in languages which makes it possible to generate code at compile time, such as Lisp with its macros, and Ruby with access to the AST. This is one thing I miss in Scala, and while I understand the reasons for it and empathize with them, I do come up some roadblocks to a scalable language now and then.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;That said, let’s analyze what happened. I tried to model my trait after the Hashable class. There are two things, though, that made my job harder than Hashable’s. First, I depended on super.equals, while hashCode doesn’t depend on its super. This becomes important as super.equals would make reference to definitions such as testSuperEquals or equateValues, and these definitions would be overridden in the subclass. Therefore, when Point3D.equals called Point.equals (its super.equals), the method Point.equals would make use of Point3D.equateValues and Point3D.testSuperEquals instead of Point.equateValues and Point.testSuperEquals.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This is difficult enough to get around, but it gets worse because, as opposed to hashCode, equals has to reference not one, but two objects. Calling a super of oneself is easy. Not so calling a super to a method on another object.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Another problem is the warning about type erasure. The case match never tests for type "This", so it is necessary to resort to reflection, to make sure we don't try to assign a superclass to a subclass. I didn't get any error on that because the hash test was returning false first. Well, fixed that, and changed the test code to produce constant hashCode.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The goal, then, is to make equals independent on any definition that might get overridden by later equals. Or, in other words, independent of any other definition related to the trait Equatable itself. Of course, it still will need to access members of the other object, and those might get overridden. That, however, is expected and shouldn’t have any influence on the equals method.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;To begin with, let’s think how our equals definition would look like in the class. In the next to last definition, we had this:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;override def equals(other : Any) = equalsTo[Point](other, true)&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;where equals was defined as&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush:scala"&gt;protected def equalsTo[This &amp;lt;: Equatable](other : Any, superEquals : =&gt; Boolean) : Boolean&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This definition delegates to the class the task of calling super.equals – or passing “true” if not appropriate.  We can’t do that inside equalsTo, because the equalsTo method is never overridden. “Super”, inside it, will have only one meaning. So this solution will do.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now, how do we deal with equateValues? One obvious solution would be doing this:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush:scala"&gt;protected def equalsTo[This &lt;: Equatable](other : Any, equateValues : Seq[Any], superEquals : =&gt; Boolean) : Boolean&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;There are at least two reasons this isn’t going to work. First, while it solves the problem of equateValues on “this” object, as it get passed as a parameter on equals’ definition, it doesn’t solve it for “that” object! In fact, we now have no way of finding out what are the elements to be compared in the other object.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;A second problem, though, might not be as obvious. We might depend on mutable data or data which isn’t computed yet at the time we define equals. Getting around that is possible, but would be much worse than defining an equals method by oneself!&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, what we’ll do is pass a function instead. A function which, given a “that” object, returns the sequence we need. Or, in other words, we want a object of this type:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush:scala"&gt;(that : This) =&gt; Seq[Any]&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The only problem with that is that “this” inside our trait does not have type This. We’ll need to receive a reference to ourselves, properly typed! Our definition, then, should be:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush:scala"&gt;protected def equalsTo[This &amp;lt;: Equatable](self : This, other : Any, equateValues : This =&gt; Seq[Any], superEquals : =&gt; Boolean) : Boolean&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The body of our function, then, becomes:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush:scala"&gt;(other : @unchecked) match {&lt;br /&gt;    case that : This =&gt;&lt;br /&gt;      (&lt;br /&gt;        that.canEqual(this)&lt;br /&gt;        &amp;amp;&amp;amp; superEquals&lt;br /&gt;        &amp;amp;&amp;amp; hashCode == that.hashCode // Can speed up or slow down &lt;br /&gt;        &amp;amp;&amp;amp; equateValues(self).zip(equateValues(that)).foldLeft(true) {&lt;br /&gt;          (equals, tuple) =&gt; equals &amp;amp;&amp;amp; tuple._1 == tuple._2&lt;br /&gt;        } &amp;amp;&amp;amp; equateValues.size == that.equateValues.size&lt;br /&gt;      )&lt;br /&gt;    case _ =&gt; false&lt;br /&gt;  }}&lt;br /&gt;}&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now, how would our equals definition look like? Here:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush:scala"&gt;override def equals(other : Any) = equalsTo[Point](this, other, that =&gt; List(that.x, that.y), true)&lt;br /&gt;override def equals(other : Any) = equalsTo[Point3D](this, other, that =&gt; List(that.z), super.equals(other))&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;For big objects, inserting the function in the parameters might be awkward.  Instead, we might prefer to assign the function to a val first. For example:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush:scala"&gt;private val pointValues = (that : Point) =&gt; List(that.x, that.y)&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, here’s everything together, with a bit of further editing for performance resons:&lt;/div&gt;&lt;div&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;trait Equatable extends scala.util.Hashable {&lt;br /&gt;  def canEqual (that : Any) : Boolean&lt;br /&gt;  &lt;br /&gt;  protected def equalsTo[This &amp;lt;: Equatable](self : This, other : Any, equateValues : This =&gt; Seq[Any], superEquals : =&gt; Boolean) : Boolean = &lt;br /&gt;    (other : @unchecked) match {&lt;br /&gt;      case that : This if self.getClass.isAssignableFrom(that.getClass) =&gt;&lt;br /&gt;        // Testing for hash code can improve or decrease performance, depending on the implementation;&lt;br /&gt;        // if hashCode gets implemented as a val, it will make equality faster&lt;br /&gt;        if (that.canEqual(this) &amp;&amp; superEquals &amp;&amp; hashCode == that.hashCode) {&lt;br /&gt;          val thisValues = equateValues(self)&lt;br /&gt;          val thatValues = equateValues(that)&lt;br /&gt;          (thisValues.zip(thatValues).foldLeft(true) { (equals, tuple) =&gt; equals &amp;&amp; tuple._1 == tuple._2 } &lt;br /&gt;           &amp;&amp; thisValues.size == thatValues.size)&lt;br /&gt;        } else false&lt;br /&gt;      case _ =&gt; false&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Point (val x : Int, val y : Int) extends Equatable {&lt;br /&gt;  override def toString = "(%d, %d)" format (x, y)&lt;br /&gt;&lt;br /&gt;  // Hashable definitions&lt;br /&gt;  // override def hashValues = List(x, y)&lt;br /&gt;  override def hashValues = List(0) // We don't want the hash skipping our tests&lt;br /&gt;  &lt;br /&gt;  // Equatable definitions&lt;br /&gt;  private val pointValues = (that : Point) =&gt; List(that.x, that.y) // one way&lt;br /&gt;  override def equals(other : Any) = equalsTo[Point](this, other, pointValues, true)&lt;br /&gt;  override def canEqual(other : Any) : Boolean = other.isInstanceOf[Point]&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Point3D(x : Int,y : Int, val z : Int) extends Point(x,y) with Equatable {&lt;br /&gt;  override def toString = "(%d, %d, %d)" format (x, y, z)&lt;br /&gt;&lt;br /&gt;  // Hashable defintions&lt;br /&gt;  // override def hashValues = List(x, y, z)&lt;br /&gt;  override def hashValues = List(0) // We don't want the hash skipping our tests&lt;br /&gt;&lt;br /&gt;  // Equatable defintions&lt;br /&gt;  // private val point3DValues = (that : Point3D) =&gt; List(that.z)&lt;br /&gt;  override def equals(other : Any) = equalsTo[Point3D](this, other, that =&gt; List(that.z), super.equals(other))&lt;br /&gt;  override def canEqual(other : Any) : Boolean = other.isInstanceOf[Point3D]&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;And the tests. I thought about doing them as assertions, but it was too silent for my taste. Anyway,&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; val x = new Point(1, 2); val x2 = new Point(1, 2)&lt;br /&gt;x: Point = (1, 2)&lt;br /&gt;x2: Point = (1, 2)&lt;br /&gt;&lt;br /&gt;scala&gt; x == x2 // super.equals does not get called, so we do not perform reference equality&lt;br /&gt;res0: Boolean = true&lt;br /&gt;&lt;br /&gt;scala&gt; val y = new Point(2, 1)&lt;br /&gt;y: Point = (2, 1)&lt;br /&gt;&lt;br /&gt;scala&gt; x == y // expected false&lt;br /&gt;res1: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; val z = new Point3D(1, 2, 0)&lt;br /&gt;z: Point3D = (1, 2, 0)&lt;br /&gt;&lt;br /&gt;scala&gt; x == z // false in that canEqual this test&lt;br /&gt;res2: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; z == x // false through reflection isAssignableFrom&lt;br /&gt;res3: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; val z2 = new Point3D(2, 1, 0)&lt;br /&gt;z2: Point3D = (2, 1, 0)&lt;br /&gt;&lt;br /&gt;scala&gt; z == z2 // expected false&lt;br /&gt;res4: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; val z3 = new Point3D(1, 2, 0)&lt;br /&gt;z3: Point3D = (1, 2, 0)&lt;br /&gt;&lt;br /&gt;scala&gt; z == z3 // expected true&lt;br /&gt;res5: Boolean = true&lt;br /&gt;&lt;br /&gt;scala&gt; val z4 = new Point3D(1, 2, 1)&lt;br /&gt;z4: Point3D = (1, 2, 1)&lt;br /&gt;&lt;br /&gt;scala&gt; z == z4 // extected false&lt;br /&gt;res6: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; x == x&lt;br /&gt;res7: Boolean = true&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-5617084856304621087?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/5617084856304621087/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/equality-scala-2.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/5617084856304621087'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/5617084856304621087'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/equality-scala-2.html' title='Equality &amp; Scala 2'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-8495350219115989912</id><published>2009-06-16T15:02:00.011-03:00</published><updated>2009-06-16T18:26:56.642-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='equality'/><category scheme='http://www.blogger.com/atom/ns#' term='language'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Equality &amp; Scala</title><content type='html'>I'm just through reading three different sources on equality in less than a week. They all said pretty much the same thing, with a minor variation here or there. It got me thinking about it, and I have some thoughts to share. For this discussion, I'll assume you are familiar with how to do equality correctly. My examples follow the model given in &lt;a href="http://www.artima.com/lejava/articles/equality.html"&gt;this article&lt;/a&gt;.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Let's start with two simple classes:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;class Point (val x : Int, val y : Int) {&lt;br /&gt; override def toString = "(%d, %d)" format (x, y)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Point3D (x : Int, y : Int, val z : Int) extends Point(x,y) {&lt;br /&gt;  override def toString = "(%d, %d, %d)" format (x, y, z)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now, a proper equality method in these classes would look like the following:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;class Point (val x : Int, val y : Int) {&lt;br /&gt;  override def toString = "(%d, %d)" format (x, y)&lt;br /&gt;  override def hashCode = 41 * (41 + x) + y&lt;br /&gt;  override def equals(other : Any) : Boolean = other match {&lt;br /&gt;    case that : Point =&gt; (&lt;br /&gt;      that.canEqual(this)&lt;br /&gt;      &amp;amp;&amp;amp; this.x == that.x&lt;br /&gt;      &amp;amp;&amp;amp; this.y == that.y&lt;br /&gt;    )&lt;br /&gt;    case _ =&gt; false&lt;br /&gt;  }&lt;br /&gt;  def canEqual(other : Any) : Boolean = other.isInstanceOf[Point]&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Point3D (x : Int, y : Int, val z : Int) extends Point(x,y) {&lt;br /&gt;  override def toString = "(%d, %d, %d)" format (x, y, z)&lt;br /&gt;  override def hashCode = 41 * (41 * (41 + x) + y) + z&lt;br /&gt;  override def equals(other : Any) : Boolean = other match {&lt;br /&gt;    case that : Point3D =&gt; (&lt;br /&gt;      that.canEqual(this)&lt;br /&gt;      &amp;amp;&amp;amp; super.equals(that)&lt;br /&gt;      &amp;amp;&amp;amp; this.z == that.z&lt;br /&gt;    )&lt;br /&gt;    case _ =&gt; false&lt;br /&gt;  }&lt;br /&gt;  override def canEqual(other : Any) : Boolean = other.isInstanceOf[Point3D]&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now, Scala has, starting with version 2.8, a Hashable trait, with which we can simplify things:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;class Point (val x : Int, val y : Int) extends scala.util.Hashable {&lt;br /&gt;  override def toString = "(%d, %d)" format (x, y)&lt;br /&gt;  override def hashValues = List(x, y)&lt;br /&gt;  override def equals(other : Any) : Boolean = other match {&lt;br /&gt;    case that : Point =&gt; (&lt;br /&gt;      that.canEqual(this)&lt;br /&gt;      &amp;amp;&amp;amp; this.x == that.x&lt;br /&gt;      &amp;amp;&amp;amp; this.y == that.y&lt;br /&gt;    )&lt;br /&gt;    case _ =&gt; false&lt;br /&gt;  }&lt;br /&gt;  def canEqual(other : Any) : Boolean = other.isInstanceOf[Point]&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Point3D (x : Int, y : Int, val z : Int) extends Point(x,y) {&lt;br /&gt;  override def toString = "(%d, %d, %d)" format (x, y, z)&lt;br /&gt;  override def hashValues = List(x, y, z)&lt;br /&gt;  override def equals(other : Any) : Boolean = other match {&lt;br /&gt;    case that : Point3D =&gt; (&lt;br /&gt;      that.canEqual(this)&lt;br /&gt;      &amp;amp;&amp;amp; super.equals(that)&lt;br /&gt;      &amp;amp;&amp;amp; this.z == that.z&lt;br /&gt;    )&lt;br /&gt;    case _ =&gt; false&lt;br /&gt;  }&lt;br /&gt;  override def canEqual(other : Any) : Boolean = other.isInstanceOf[Point3D]&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;While it doesn't seem to have gained us anything, it might for larger objects, and, at any rate, it removes the "magic" of a hash code, and let someone else worry how to do it.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Still, there's a lot of stuff in there just to get equality right, and these are pretty simple classes. What we see is a &lt;i&gt;programming pattern&lt;/i&gt;, but one so common and so important that, in my opinion, it merits special attention from the language itself.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Barring that, let's see what we can do programmatically about it. I'll start with a helper function, and how it would be used:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;def testEquality(one : AnyRef, other : AnyRef, elementsOne : Seq[Any], elementsOther : Seq[Any]) : Boolean = {&lt;br /&gt;  val classOfOne = one.getClass&lt;br /&gt;  val classOfOther = other.getClass&lt;br /&gt;&lt;br /&gt;  def sameClassOrSubclass: Boolean = classOfOne.isAssignableFrom(classOfOther)&lt;br /&gt;&lt;br /&gt;  def superEquals : Boolean = try {&lt;br /&gt;    val superEqualsMethod = classOfOne.getSuperclass.getMethod("equals", classOf[Any])&lt;br /&gt;    if (superEqualsMethod.getDeclaringClass != classOf[Any])&lt;br /&gt;      superEqualsMethod.invoke(one, other) match {&lt;br /&gt;        case flag : java.lang.Boolean =&gt; flag.booleanValue // Translate boxed boolean into boolean&lt;br /&gt;        case _ =&gt; error("Method equals on the parent class of object " + one + " does not return a boolean")&lt;br /&gt;      }&lt;br /&gt;    else true&lt;br /&gt;  } catch {&lt;br /&gt;    case _ =&gt; true&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  def canEqual : Boolean = try {&lt;br /&gt;    val canEqualMethod = classOfOther.getMethod("canEqual", classOf[Any])&lt;br /&gt;    canEqualMethod.invoke(other, one) match {&lt;br /&gt;      case flag : java.lang.Boolean =&gt; flag.booleanValue // Translate boxed boolean into boolean&lt;br /&gt;      case _ =&gt; error("Method canEqual on object " + other + " does not return a boolean")&lt;br /&gt;    }&lt;br /&gt;  } catch {&lt;br /&gt;    case _ =&gt; true&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  def elementsEquals : Boolean = {&lt;br /&gt;    elementsOne.zip(elementsOther).foldLeft(true) {&lt;br /&gt;      (equals, pair) =&gt; equals &amp;amp;&amp;amp; pair._1 == pair._2&lt;br /&gt;    } &amp;amp;&amp;amp; elementsOne.size == elementsOther.size&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  (sameClassOrSubclass(classOfOne, classOfOther)&lt;br /&gt;    &amp;amp;&amp;amp; canEqual&lt;br /&gt;    &amp;amp;&amp;amp; superEquals&lt;br /&gt;    &amp;amp;&amp;amp; elementsEquals&lt;br /&gt;  )&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Point (val x : Int, val y : Int) extends scala.util.Hashable {&lt;br /&gt;  override def toString = "(%d, %d)" format (x, y)&lt;br /&gt;&lt;br /&gt;  // Hashable&lt;br /&gt;  override def hashValues = List(x, y)&lt;br /&gt;&lt;br /&gt;  // Equality&lt;br /&gt;  override def equals(other : Any) : Boolean = other match {&lt;br /&gt;    case that : Point =&gt; testEquality(this, that, List(x, y), List(that.x, that.y))&lt;br /&gt;    case _ =&gt; false&lt;br /&gt;  }&lt;br /&gt;  def canEqual(other : Any) : Boolean = other.isInstanceOf[Point]&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Point3D(x : Int,y : Int, val z : Int) extends Point(x,y) {&lt;br /&gt;  override def toString = "(%d, %d, %d)" format (x, y, z)&lt;br /&gt;&lt;br /&gt;  // Hashable&lt;br /&gt;  override def hashValues = List(x, y)&lt;br /&gt;&lt;br /&gt;  // Equality&lt;br /&gt;  override def equals(other : Any) : Boolean = other match {&lt;br /&gt;    case that : Point3D =&gt; testEquality(this, that, List(x, y, z), List(that.x, that.y, that.z))&lt;br /&gt;    case _ =&gt; false&lt;br /&gt;  }&lt;br /&gt;  override def canEqual(other : Any) : Boolean = other.isInstanceOf[Point3D]&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now, this method  always calls the parent's equals, unless it's Any's equals. You might want to parametrize this. Also, it expects canEqual to be defined if needed, which might lead to bugs. Furthermore, its usage of reflection makes it slower than needed. Finally, the definition of equals is not that much simpler than what we had before.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, can we do better? Ideally, one could build a trait similar to Hashable, but it turns out that is not that simple. Let's try:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;trait Equatable extends scala.util.Hashable {&lt;br /&gt;  protected type EquateThis &amp;lt;: Equatable&lt;br /&gt;  private def equalsFromAny : Boolean = {&lt;br /&gt;    this.getClass.getSuperclass.getMethod("equals", classOf[Any])&lt;br /&gt;    .getDeclaringClass == classOf[Any]&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  protected def equateValues : Seq[Any]&lt;br /&gt;&lt;br /&gt;  def canEqual (that : Any) : Boolean = true&lt;br /&gt;&lt;br /&gt;  abstract override def equals(other : Any) : Boolean = (other : @unchecked) match {&lt;br /&gt;    case that : EquateThis =&gt;&lt;br /&gt;      (&lt;br /&gt;        that.canEqual(this)&lt;br /&gt;        &amp;amp;&amp;amp; (equalsFromAny || super.equals(that))&lt;br /&gt;        &amp;amp;&amp;amp; hashCode == that.hashCode // Can speed up or slow down&lt;br /&gt;        &amp;amp;&amp;amp; equateValues.zip(that.equateValues).foldLeft(true) {&lt;br /&gt;          (equals, tuple) =&gt; equals &amp;amp;&amp;amp; tuple._1 == tuple._2&lt;br /&gt;        } &amp;amp;&amp;amp; equateValues.size == that.equateValues.size&lt;br /&gt;      )&lt;br /&gt;    case _ =&gt; false&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Point (val x : Int, val y : Int) extends Equatable {&lt;br /&gt;  override def toString = "(%d, %d)" format (x, y)&lt;br /&gt;&lt;br /&gt;  // Hashable definitions&lt;br /&gt;  override def hashValues = List(x, y)&lt;br /&gt;&lt;br /&gt;  // Equatable definitions&lt;br /&gt;  override type EquateThis = Point&lt;br /&gt;  override def equateValues = List(x, y)&lt;br /&gt;  override def canEqual(other : Any) : Boolean = other.isInstanceOf[Point]&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Point3D(x : Int,y : Int, val z : Int) extends Point(x,y) with Equatable {&lt;br /&gt;  override def toString = "(%d, %d, %d)" format (x, y, z)&lt;br /&gt;&lt;br /&gt;  // Hashable defintions&lt;br /&gt;  override def hashValues = List(x, y, z)&lt;br /&gt;&lt;br /&gt;  // Equatable defintions&lt;br /&gt;  override type EquateThis = Point3D&lt;br /&gt;  override def canEqual(other : Any) : Boolean = other.isInstanceOf[Point3D]&lt;br /&gt;  override def equateValues = List(z)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;That looks more like it, but it has a few problems still. It still uses reflection, for one thing, to test for super's equals method. Also, you can't parametrize that is it is. It won't get Equatable's own equals, though, as traits compiles down to part of the class being defined, not as an ancestor to it.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Next, it has a default for canEqual, and a dangerous one at that. If the programmer forgets to override it, it will lead to trouble.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;But, most importantly, &lt;i&gt;it doesn't work&lt;/i&gt;. The class Point3D can't override Point's definition for type EquateThis. I don't understand precisely why this is the case, and I'd be glad if anyone stepped in to explain this.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Anyway, let fix these problems:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;trait Equatable extends scala.util.Hashable {&lt;br /&gt;  protected def testSuperEquals : Boolean&lt;br /&gt;  protected def equateValues : Seq[Any]&lt;br /&gt;  def canEqual (that : Any) : Boolean&lt;br /&gt;&lt;br /&gt;  protected def equalsTo[This &amp;lt;: Equatable](other : Any) : Boolean = (other : @unchecked) match {&lt;br /&gt;    case that : This =&gt;&lt;br /&gt;      (&lt;br /&gt;        that.canEqual(this)&lt;br /&gt;        &amp;amp;&amp;amp; ((!testSuperEquals) || super.equals(that))&lt;br /&gt;        &amp;amp;&amp;amp; hashCode == that.hashCode // Can speed up or slow down&lt;br /&gt;        &amp;amp;&amp;amp; equateValues.zip(that.equateValues).foldLeft(true) {&lt;br /&gt;          (equals, tuple) =&gt; equals &amp;amp;&amp;amp; tuple._1 == tuple._2&lt;br /&gt;        } &amp;amp;&amp;amp; equateValues.size == that.equateValues.size&lt;br /&gt;      )&lt;br /&gt;    case _ =&gt; false&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Point (val x : Int, val y : Int) extends Equatable {&lt;br /&gt;  override def toString = "(%d, %d)" format (x, y)&lt;br /&gt;&lt;br /&gt;  // Hashable definitions&lt;br /&gt;  override def hashValues = List(x, y)&lt;br /&gt;&lt;br /&gt;  // Equatable definitions&lt;br /&gt;  override def testSuperEquals = false&lt;br /&gt;  override def equateValues = List(x, y)&lt;br /&gt;  override def equals(other : Any) = equalsTo[Point](other)&lt;br /&gt;  override def canEqual(other : Any) : Boolean = other.isInstanceOf[Point]&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Point3D(x : Int,y : Int, val z : Int) extends Point(x,y) with Equatable {&lt;br /&gt;  override def toString = "(%d, %d, %d)" format (x, y, z)&lt;br /&gt;&lt;br /&gt;  // Hashable defintions&lt;br /&gt;  override def hashValues = List(x, y, z)&lt;br /&gt;&lt;br /&gt;  // Equatable defintions&lt;br /&gt;  override def testSuperEquals = true&lt;br /&gt;  override def equals(other : Any) = equalsTo[Point3D](other)&lt;br /&gt;  override def canEqual(other : Any) : Boolean = other.isInstanceOf[Point3D]&lt;br /&gt;  override def equateValues = List(z)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;This finally get us where we wanted. Or as close to as I could, at least. :-)&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The definition of canEqual is made abstract. That forces the first class to mix Equatable in to define it, even if to a default of "true". Next, instead of trying to figure out if equality must be called on the super, we simply require the class to tell us.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Finally, the equals method. We can't (or I couldn't) get the trait to define it, but I got pretty close. In the end, class still has to define an equals method, but that method pretty much gets reduced to a simple call to one defined in the trait, passing the object being compared to and the class expected. The class expected gets passed as an explicit type parametrization.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Neat. I didn't think I'd be able to get this much! Now, who's going to port it to Java?&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Update:&lt;/b&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Ok, I spoke too soon. This method fails here:&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; val x = new Point(1, 2); val x2 = new Point(1, 2)&lt;br /&gt;x: Point = (1, 2)&lt;br /&gt;x2: Point = (1, 2)&lt;br /&gt;&lt;br /&gt;scala&gt; x == x2 // super.equals does not get called, so we do not perform reference equality&lt;br /&gt;res7: Boolean = true&lt;br /&gt;&lt;br /&gt;scala&gt; val y = new Point(2, 1)&lt;br /&gt;y: Point = (2, 1)&lt;br /&gt;&lt;br /&gt;scala&gt; x == y // expected false&lt;br /&gt;res8: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; val z = new Point3D(1, 2, 0)&lt;br /&gt;z: Point3D = (1, 2, 0)&lt;br /&gt;&lt;br /&gt;scala&gt; x == z // false in the canEqual call&lt;br /&gt;res9: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; z == x // false in the type check&lt;br /&gt;res10: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; val z2 = new Point3D(2, 1, 0)&lt;br /&gt;z2: Point3D = (2, 1, 0)&lt;br /&gt;&lt;br /&gt;scala&gt; z == z2 // false in the super.equals call&lt;br /&gt;res11: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; val z3 = new Point3D(1, 2, 0)&lt;br /&gt;z3: Point3D = (1, 2, 0)&lt;br /&gt;&lt;br /&gt;scala&gt; z == z3 // false in the super.super.equals call - it should have been true&lt;br /&gt;res12: Boolean = false&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Anyone up for fixing it?&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Update 2:&lt;/b&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Ok, I fixed it. I resorted to delegating this task to the calling class. That means I do away with testSuperEquals, but require a second parameter to equalsTo. I make it by name, so that it doesn't get evaluated needlessly.&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;trait Equatable extends scala.util.Hashable {&lt;br /&gt;  protected def equateValues : Seq[Any]&lt;br /&gt;  def canEqual (that : Any) : Boolean&lt;br /&gt;  &lt;br /&gt;  protected def equalsTo[This &amp;lt;: Equatable](other : Any, superEquals : =&gt; Boolean) : Boolean = (other : @unchecked) match {&lt;br /&gt;    case that : This =&gt;&lt;br /&gt;      (&lt;br /&gt;        that.canEqual(this)&lt;br /&gt;        &amp;&amp; superEquals&lt;br /&gt;        &amp;&amp; hashCode == that.hashCode // Can speed up or slow down &lt;br /&gt;        &amp;&amp; equateValues.zip(that.equateValues).foldLeft(true) {&lt;br /&gt;          (equals, tuple) =&gt; equals &amp;&amp; tuple._1 == tuple._2&lt;br /&gt;        } &amp;&amp; equateValues.size == that.equateValues.size&lt;br /&gt;      )&lt;br /&gt;    case _ =&gt; false&lt;br /&gt;  }}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Point (val x : Int, val y : Int) extends Equatable {&lt;br /&gt;  override def toString = "(%d, %d)" format (x, y)&lt;br /&gt;&lt;br /&gt;  // Hashable definitions&lt;br /&gt;  override def hashValues = List(x, y)&lt;br /&gt;  &lt;br /&gt;  // Equatable definitions&lt;br /&gt;  override def equateValues = List(x, y)&lt;br /&gt;  override def equals(other : Any) = equalsTo[Point](other, true)&lt;br /&gt;  override def canEqual(other : Any) : Boolean = other.isInstanceOf[Point]&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Point3D(x : Int,y : Int, val z : Int) extends Point(x,y) with Equatable {&lt;br /&gt;  override def toString = "(%d, %d, %d)" format (x, y, z)&lt;br /&gt;&lt;br /&gt;  // Hashable defintions&lt;br /&gt;  override def hashValues = List(x, y, z)&lt;br /&gt;&lt;br /&gt;  // Equatable defintions&lt;br /&gt;  override def equals(other : Any) = equalsTo[Point3D](other, super.equals(other))&lt;br /&gt;  override def canEqual(other : Any) : Boolean = other.isInstanceOf[Point3D]&lt;br /&gt;  override def equateValues = List(z)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;And the testing:&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; val x = new Point(1, 2); val x2 = new Point(1, 2)&lt;br /&gt;x: Point = (1, 2)&lt;br /&gt;x2: Point = (1, 2)&lt;br /&gt;&lt;br /&gt;scala&gt; x == x2 // super.equals does not get called, so we do not perform reference equality&lt;br /&gt;res105: Boolean = true&lt;br /&gt;&lt;br /&gt;scala&gt; val y = new Point(2, 1)&lt;br /&gt;y: Point = (2, 1)&lt;br /&gt;&lt;br /&gt;scala&gt; x == y // expected false&lt;br /&gt;res106: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; val z = new Point3D(1, 2, 0)&lt;br /&gt;z: Point3D = (1, 2, 0)&lt;br /&gt;&lt;br /&gt;scala&gt; x == z // false in the canEqual call&lt;br /&gt;res107: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; z == x // false in the type check&lt;br /&gt;res108: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; val z2 = new Point3D(2, 1, 0)&lt;br /&gt;z2: Point3D = (2, 1, 0)&lt;br /&gt;&lt;br /&gt;scala&gt; z == z2 // false in the super.equals call&lt;br /&gt;res109: Boolean = true&lt;br /&gt;&lt;br /&gt;scala&gt; val z3 = new Point3D(1, 2, 0)&lt;br /&gt;z3: Point3D = (1, 2, 0)&lt;br /&gt;&lt;br /&gt;scala&gt; z == z3 // expected true&lt;br /&gt;res110: Boolean = true&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;b&gt;Update 3:&lt;/b&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This is still seriously broken, as the very test above indicates. What is happening is that when super.equals gets called, it uses this.equateValues instead of the super's version of it. It might be easy to fix for "this", but not for "that". At this point, I'm giving up on super.equals. Let's assume the equality for all classes is defined by the equalsTo method, and require a call to super.equateValues at every subclass (that finds it necessary). Here it is&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;trait Equatable extends scala.util.Hashable {&lt;br /&gt;  protected def equateValues : Seq[Any]&lt;br /&gt;  def canEqual (that : Any) : Boolean&lt;br /&gt;  &lt;br /&gt;  protected def equalsTo[This &lt;: Equatable](other : Any) : Boolean = (other : @unchecked) match {&lt;br /&gt;    case that : This =&gt;&lt;br /&gt;      (&lt;br /&gt;        that.canEqual(this)&lt;br /&gt;        &amp;&amp; hashCode == that.hashCode // Can speed up or slow down &lt;br /&gt;        &amp;&amp; equateValues.zip(that.equateValues).foldLeft(true) {&lt;br /&gt;          (equals, tuple) =&gt; equals &amp;&amp; tuple._1 == tuple._2&lt;br /&gt;        } &amp;&amp; equateValues.size == that.equateValues.size&lt;br /&gt;      )&lt;br /&gt;    case _ =&gt; false&lt;br /&gt;  }}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Point (val x : Int, val y : Int) extends Equatable {&lt;br /&gt;  override def toString = "(%d, %d)" format (x, y)&lt;br /&gt;&lt;br /&gt;  // Hashable definitions&lt;br /&gt;  override def hashValues = List(x, y)&lt;br /&gt;  &lt;br /&gt;  // Equatable definitions&lt;br /&gt;  override def equateValues = List(x, y)&lt;br /&gt;  override def equals(other : Any) = equalsTo[Point](other)&lt;br /&gt;  override def canEqual(other : Any) : Boolean = other.isInstanceOf[Point]&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Point3D(x : Int,y : Int, val z : Int) extends Point(x,y) with Equatable {&lt;br /&gt;  override def toString = "(%d, %d, %d)" format (x, y, z)&lt;br /&gt;&lt;br /&gt;  // Hashable defintions&lt;br /&gt;  override def hashValues = List(x, y, z)&lt;br /&gt;&lt;br /&gt;  // Equatable defintions&lt;br /&gt;  override def equals(other : Any) = equalsTo[Point3D](other)&lt;br /&gt;  override def canEqual(other : Any) : Boolean = other.isInstanceOf[Point3D]&lt;br /&gt;  override def equateValues = z :: super.equateValues&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;And test:&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; val x = new Point(1, 2); val x2 = new Point(1, 2)&lt;br /&gt;x: Point = (1, 2)&lt;br /&gt;x2: Point = (1, 2)&lt;br /&gt;&lt;br /&gt;scala&gt; x == x2 // super.equals does not get called, so we do not perform reference equality&lt;br /&gt;res138: Boolean = true&lt;br /&gt;&lt;br /&gt;scala&gt; val y = new Point(2, 1)&lt;br /&gt;y: Point = (2, 1)&lt;br /&gt;&lt;br /&gt;scala&gt; x == y // expected false&lt;br /&gt;res139: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; val z = new Point3D(1, 2, 0)&lt;br /&gt;z: Point3D = (1, 2, 0)&lt;br /&gt;&lt;br /&gt;scala&gt; x == z // false in the canEqual call&lt;br /&gt;res140: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; z == x // false in the type check&lt;br /&gt;res141: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; val z2 = new Point3D(2, 1, 0)&lt;br /&gt;z2: Point3D = (2, 1, 0)&lt;br /&gt;&lt;br /&gt;scala&gt; z == z2 // expected false&lt;br /&gt;res142: Boolean = false&lt;br /&gt;&lt;br /&gt;scala&gt; val z3 = new Point3D(1, 2, 0)&lt;br /&gt;z3: Point3D = (1, 2, 0)&lt;br /&gt;&lt;br /&gt;scala&gt; z == z3 // expected true&lt;br /&gt;res143: Boolean = true&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-8495350219115989912?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/8495350219115989912/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/equality-scala.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8495350219115989912'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/8495350219115989912'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/equality-scala.html' title='Equality &amp; Scala'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-6426513655300353647</id><published>2009-06-11T23:05:00.009-03:00</published><updated>2009-06-12T13:33:07.383-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='collection'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='language'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Using Implicits to Select Types</title><content type='html'>Scala 2.8's collection revision is doing interesting things. The most obvious one will be the methods revision. One thing that shouldn't be all that obvious, though, is how much code will be shared, and how that shared code will still look like it was specific to a class.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I'll quote here a couple of examples from the &lt;a href="http://www.scala-lang.org/sid/3#"&gt;Scala 2.8 Collection's Whitepaper&lt;/a&gt; (pdf at the bottom):&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; "abc" map (x =&gt; (x + 1).toChar)&lt;br /&gt;res1: scala.runtime.RichString = bcd&lt;br /&gt;&lt;br /&gt;scala&gt; "abc" map (x =&gt; (x + 1))&lt;br /&gt;res2: scala.collection.immutable.Vector[Int] = Vector(98, 99, 100)&lt;br /&gt;&lt;br /&gt;scala&gt; Map("a" -&gt; 1, "b" -&gt; 2) map { case (x, y) =&gt; (y, x) }&lt;br /&gt;res3: scala.collection.immutable.Map[Int,java.lang.String] = Map(1 -&gt; a, 2 -&gt; b)&lt;br /&gt;&lt;br /&gt;scala&gt; Map("a" -&gt; 1, "b" -&gt; 2) map { case (x, y) =&gt; y }&lt;br /&gt;res4: scala.collection.immutable.Iterable[Int] = List(1, 2)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;&lt;div&gt;Now, this "map" method is inherited from a common trait, and yet it knows when the result of a map over a RichString is a RichString, when the result of a map over a Map is a Map, and when it's not. How can it be?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The answer is implicit parameters. One thing about implicits, is that a more specific implicit has preference over a more generic one. Take a look at this example:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; abstract class X[T] { def id : Unit }&lt;br /&gt;defined class X&lt;br /&gt;&lt;br /&gt;scala&gt; implicit def a[T] = new X[T] { def id = println("generic") }&lt;br /&gt;a: [T]X[T]&lt;br /&gt;&lt;br /&gt;scala&gt; implicit def b = new X[Int] { def id = println("Int") }&lt;br /&gt;b: X[Int]&lt;br /&gt;&lt;br /&gt;scala&gt; def f[T](a : T)(implicit g : X[T]) = g.id&lt;br /&gt;f: [T](T)(implicit X[T])Unit&lt;br /&gt;&lt;br /&gt;scala&gt; f(5)&lt;br /&gt;Int&lt;br /&gt;&lt;br /&gt;scala&gt; f('c')&lt;br /&gt;generic&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Both "a" and "b" have the correct type, X[T]. The second definition, though, will return X[Int], which is more specific than X[T], which the first definition returns. So, whenever X[Int] is required, "b" will take precedence over "a". Naturally, if some other type of X is required, "b" won't be used at all.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This is how map can do its trick. To compose the result, it uses methods from the class Builder[-Elem, +To]. Such a build will create a collection of type To from elements of type Elem. Now, this is not enough to solve map's problem. For example, I want a RichString as result, if I'm doing a map over a RichString, but not if I'm mapping over a List of Chars. See the two examples below:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; "abc" map (x =&gt; (x + 1).toChar)&lt;br /&gt;res1: scala.runtime.RichString = bcd&lt;br /&gt;&lt;br /&gt;scala&gt; List('a', 'b', 'c') map (x =&gt; (x + 1).toChar)&lt;br /&gt;res11: List[Char] = List(b, c, d)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;So, for methods with more complex semantics, like map, we need something else which can produce the correct Builder. For that, the trait BuilderFactory[Elem,&lt;/div&gt;&lt;div&gt;+To, From] exists. BuilderFactory will produce a Builder for a method which takes a collection of type From, and uses elements of type Elem to produce a collection of type To.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now, the more generic implicit for a BuilderFactory is BuilderFactory[A, Iterable[A], Iterable[_]], which should be pretty obvious. Other implicits exists, though, such as BuilderFactory[Char, RichString, RichString]. Now, look at map's declaration:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;def map[B, That](p: Elem =&gt; B)(implicit bf: BuilderFactory[B, That, This]): That&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, when you do "abc".map( x =&gt; (x + 1).toChar), the compiler knows that "B" is Char (the result of the function being mapped). "This" is known to be RichString, from the definition of class RichString itself. Now, given that "B" = Char and "This" = RichString, then BuilderFactory[Char, RichString, RichString] is a more specific match than the other implicit definitions. And, because it gets used, "That" gets defined to be RichString also, thus defining the result type for that map.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The cleverness of it is to use implicits to define unknown type parameters as a function of known type parameters. This is can be a very useful pattern for those who want to take maximum advantage of static type checking.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-6426513655300353647?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/6426513655300353647/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/using-implicits-to-select-types.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/6426513655300353647'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/6426513655300353647'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/using-implicits-to-select-types.html' title='Using Implicits to Select Types'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-2658089081403778482</id><published>2009-06-11T17:36:00.004-03:00</published><updated>2009-06-11T17:46:28.642-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='case class'/><category scheme='http://www.blogger.com/atom/ns#' term='language'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Case Classes and Product</title><content type='html'>It's a well-known fact that by adding "case" before "class" in Scala, the compiler will generate some scaffolding for you like making all your paremeters "val", creating apply and unapply in a companion object. etc.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;It's not a particular known fact that one of the things it does is extending the class with the trait Product. This trait makes it easy to access the elements of the class, like in the example below:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; trait recordType {&lt;br /&gt;     |   self : Product =&gt;&lt;br /&gt;     |   def records : String = (&lt;br /&gt;     |     for(parm &lt;- self.productIterator)&lt;br /&gt;     |       yield parm.asInstanceOf[AnyRef].getClass.getSimpleName+": "+parm&lt;br /&gt;     |     ) mkString "\n"&lt;br /&gt;     | }&lt;br /&gt;defined trait recordType&lt;br /&gt;&lt;br /&gt;scala&gt; case class X(i : Int, c : Char, s : String) extends recordType&lt;br /&gt;defined class X&lt;br /&gt;&lt;br /&gt;scala&gt; val x = X(5, 'd', "this")&lt;br /&gt;x: X = X(5,d,this)&lt;br /&gt;&lt;br /&gt;scala&gt; println(x.records)&lt;br /&gt;Integer: 5&lt;br /&gt;Character: d&lt;br /&gt;String: this&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Let me talk about the trait recordType a bit first. Its body first line declares that "self : Product =&gt;". This has two purposes. First, it creates an alias for "this". Second, and most important, it tells the compiler that to be able to use this trait, a class must mix in the trait Product.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Anyway, the code works fine for simple classes, but it might be weird for collections:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; case class Y(a : Array[String], l : List[Int]) extends recordType&lt;br /&gt;defined class Y&lt;br /&gt;&lt;br /&gt;scala&gt; val y = Y(Array("this", "example"), List(1,2,3))&lt;br /&gt;y: Y = Y([Ljava.lang.String;@60a517,List(1, 2, 3))&lt;br /&gt;&lt;br /&gt;scala&gt; println(y.records)&lt;br /&gt;String[]: [Ljava.lang.String;@60a517&lt;br /&gt;$colon$colon: List(1, 2, 3)&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Here, Array is mucked up because Java's Array are mucked up. As for the List, any non-empty List actually belongs to class "::", a subclass of List.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-2658089081403778482?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/2658089081403778482/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/case-classes-and-product.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/2658089081403778482'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/2658089081403778482'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/case-classes-and-product.html' title='Case Classes and Product'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-244889593461414375</id><published>2009-06-07T18:15:00.004-03:00</published><updated>2009-06-17T23:52:19.511-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='currying'/><category scheme='http://www.blogger.com/atom/ns#' term='tuples'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='language'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Function.tupled, Function.curried</title><content type='html'>Scala's library hides small gems of which little is said. Let me speak of a personal favorite here, the object Function.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This object has a number of methods to construct a function from another function (or others, in the case of "chain").  They are variations of "curried", "tupled", "uncurried" and "untupled". As their names makes clear, they transform a function whose arguments are not curried or are not a tuple into a function whose arguments are curried, or which receives a tuple as an argument. Take, for instance, this definition of zipMap, which applies a function of two arguments between two lists:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; def zipMap[A,B,C](l1 : Seq[A], l2 : Seq[B])(f : (A,B) =&gt; C) =&lt;br /&gt;     | l1 zip l2 map (x =&gt; f(x._1, x._2))&lt;br /&gt;zipMap: [A,B,C](l1: Seq[A],l2: Seq[B])(f: (A, B) =&gt; C)Sequence[C]&lt;br /&gt;&lt;br /&gt;scala&gt; zipMap (List(1, 3, 9), List(5, 2, 3)) ((x,y) =&gt; x max y)&lt;br /&gt;res5: Sequence[Int] = List(5, 3, 9)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This is not a bad definition, but accessing the tuple arguments to pass to f is too much mechanics for my taste. So, instead, we could do this:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;scala&gt; def zipMap[A,B,C](l1 : Seq[A], l2 : Seq[B])(f : (A,B) =&gt; C) =&lt;br /&gt;     | l1 zip l2 map Function.tupled(f)&lt;br /&gt;zipMap: [A,B,C](l1: Seq[A],l2: Seq[B])(f: (A, B) =&gt; C)Sequence[C]&lt;br /&gt;&lt;br /&gt;scala&gt; zipMap (List(1, 3, 9), List(5, 2, 3)) ((x,y) =&gt; x max y)&lt;br /&gt;res4: Sequence[Int] = List(5, 3, 9)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Much better, don't you think? By the way, this was done on 2.8, where Seq has the method zip.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-244889593461414375?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/244889593461414375/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/functiontupled-functioncurried.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/244889593461414375'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/244889593461414375'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/functiontupled-functioncurried.html' title='Function.tupled, Function.curried'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-5495399006211742805</id><published>2009-06-05T22:54:00.008-03:00</published><updated>2009-12-09T12:49:18.874-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='scalable-series'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='language'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Scalable Algorithms 3</title><content type='html'>Back to matching shortcuts to menu options, I decided my best option would be a &lt;a href="http://en.wikipedia.org/wiki/Deterministic_finite-state_machine"&gt;deterministic finite automaton&lt;/a&gt;. It would make excellent use of partial input, and take much less space than a set of all possible inputs accepted -- to make use of state machine lingo -- by each menu option.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now, anyone who has ever worked with DFA before will tell you that the trick to build one is to first generate the &lt;a href="http://en.wikipedia.org/wiki/Regular_expression"&gt;regular expression&lt;/a&gt; which represents what you want to match. Yes, that's your good, old RegExp. Well, not fully... you can't have back references, for one thing. But most of what you think of as regexp will do.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, what regular expression would match our input? Let's take a small menu option: "New Tab". We want to accept either word as well as its abbreviation, so "New", "Tab" and "NT" should be matched. Any prefix of either word should be taken as well, so we add "N", "Ne", "T" and "Ta" to it. Finally, we want to combine word prefixes, like "NTab" or "NeTa", you get the idea.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, let's get the first word, and see how far we can take. We have "N", "Ne" and "New". So "N" is mandatory, and "e" is optional. That would be "Ne?" in regexp. Next, "w" is also optional, but it can only appear if "e" appears as well. That's "N(ew?)?" in regexp, or, to make regular use of parenthesis, "N(e(w)?)?". Now, since we may as well only match the second word, the whole first word is optional, which gives us "(N(e(w)?)?)?".&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Naturally, each word would follow the same pattern, but what about the whole menu option? As it happens, you only have to concatenate the patterns: "(N(e(w)?)?)?(T(a(b)?)?)?". It should be pretty simply to create such a function.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;In fact, we can do it using foldRight. As you know, foldRight combines things from right to left, using the result of the last operation and the next element. Now, it may not be immediately obvious what the operation is, so let's assume we already processed "w". That means we have "(w)?" as the last result, and "e" as the next letter, and the result we want to come up with is "(e(w)?)?". It's trivial to see, then, that the operation is "("+"e"+"(w)?"+")?".&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now that we know what the operation is, let's think about the initial "result" that fold takes as parameter. We want x in "("+"w"+x+")?". Since that must be equal to "(w)?", x = "".&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Ok, so now we know what the regular expression for a menu option must look like, as well as how to build one from its string. We can now proceed to building a DFA.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;But... we can match regular expressions to strings just as well as DFA. I might not take advantage of partial inputs, and I can't go the next step, which is creating one DFA which will accept &lt;span class="Apple-style-span" style="font-style: italic;"&gt;all&lt;/span&gt; menu options and, as an added bonus, have the associated menu options at each state.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Still, how hard would it be to match against regexp? Well, let's try...&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;val wordsep = "\\W+"&lt;br /&gt;def words(s : String) = s.split(wordsep)&lt;br /&gt;def phraseRegex(s : String) = &lt;br /&gt;  "^" + words(s).map(_.foldRight("")("(" + _ + _ + ")?")).mkString&lt;br /&gt;def regexList(l : List[String]) = l.map(s =&gt; phraseRegex(s) -&gt; s)&lt;br /&gt;def regexSearcher(l : List[String]) = {&lt;br /&gt;  val r = regexList(l)&lt;br /&gt;  (s : String) =&gt; r.filter(s matches _._1).map(_._2)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;That's it. You could, and should improve it by pre-compiling the regexp expressions. It's a bit uglier, but for the sake of doing things right, I'll post it at the end. Anyway, this is fairly inexpensive in terms of memory usage, and regexp matches are very fast. I doubt it can beat a hash tree, but it should give it a run for its money. Still, the fact that you'll be matching &lt;span class="Apple-style-span" style="font-style: italic;"&gt;every&lt;/span&gt; menu option against the input is problematic, and the hash tree doesn't suffer that problem. The setup time for this algorithm should be pretty fast too, even precompiling the regexp.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Anyway, it's short, it's obvious, and it's not too shabby. We'll next get into DFA, and do it by using Scala's standard library. That should be the worst of all algorithms, but a stepping stone to the last one I'll present. For now, here's the revised code.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:scala"&gt;&lt;br /&gt;val wordsep = "\\W+"&lt;br /&gt;def words(s : String) = s.split(wordsep)&lt;br /&gt;def phraseRegex(s : String) = &lt;br /&gt;  ("^" + words(s).map(_.foldRight("")("(" + _ + _ + ")?")).mkString).r&lt;br /&gt;def regexList(l : List[String]) = l.map(s =&gt; phraseRegex(s) -&gt; s)&lt;br /&gt;def regexSearcher(l : List[String]) = {&lt;br /&gt;  val r = regexList(l)&lt;br /&gt;  (s : String) =&gt; r.filter(_._1.findPrefixOf(s) == Some(s)).map(_._2)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-5495399006211742805?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/5495399006211742805/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/scalable-algorithms-3.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/5495399006211742805'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/5495399006211742805'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/scalable-algorithms-3.html' title='Scalable Algorithms 3'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-7509854062279127236</id><published>2009-06-03T21:03:00.003-03:00</published><updated>2009-06-03T21:18:07.456-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='compiler'/><category scheme='http://www.blogger.com/atom/ns#' term='language'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Compiling Remotely</title><content type='html'>As you may know, the fsc compiler, the recommended way to compile Scala, and used by the Scala interpreter by default, detaches a daemon service the first time it is run. After that, fsc will always call the daemon service to compile for it, to save time.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;It does this through TCP, which begs the question... can I compile remotely? The answer is Yes! It's not documented, and it is a bit awkward, but...&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;First, you get fsc running on the server by running fsc -verbose, like this:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush:plain"&gt;&lt;br /&gt;$fsc -verbose&lt;br /&gt;[Server arguments: -d C:\Users\Daniel\Documents\Programas\. -verbose]&lt;br /&gt;[VM arguments: ]&lt;br /&gt;[Temp directory: C:\PROGRA~1\Scala\bin\..\var\scala-devel]&lt;br /&gt;[Executed command: C:\PROGRA~1\Scala\bin\..\bin\scala.bat scala.tools.nsc.CompileServer]&lt;br /&gt;[Port number: 1385]&lt;br /&gt;[Connected to compilation daemon at port 1385]&lt;br /&gt;Usage: fsc &lt;options&gt; &lt;source files&gt;&lt;br /&gt;where possible standard options include:&lt;br /&gt;  -g:&lt;g&gt;                       Specify level of generated debugging info (none,source,line,vars,notailcalls)&lt;br /&gt;  -nowarn                      Generate no warnings&lt;br /&gt;  -verbose                     Output messages about what the compiler is doing&lt;br /&gt;  -deprecation                 Output source locations where deprecated APIs are used&lt;br /&gt;  -unchecked                   Enable detailed unchecked warnings&lt;br /&gt;  -classpath &lt;path&gt;            Specify where to find user class files&lt;br /&gt;  -sourcepath &lt;path&gt;           Specify where to find input source files&lt;br /&gt;  -bootclasspath &lt;path&gt;        Override location of bootstrap class files&lt;br /&gt;  -extdirs &lt;dirs&gt;              Override location of installed extensions&lt;br /&gt;  -d &lt;directory&gt;               Specify where to place generated class files&lt;br /&gt;  -encoding &lt;encoding&gt;         Specify character encoding used by source files&lt;br /&gt;  -target:&lt;target&gt;             Specify for which target object files should be built (jvm-1.5,jvm-1.4,msil)&lt;br /&gt;  -print                       Print program with all Scala-specific features removed&lt;br /&gt;  -optimise                    Generates faster bytecode by applying optimisations to the program&lt;br /&gt;  -explaintypes                Explain type errors in more detail&lt;br /&gt;  -uniqid                      Print identifiers with unique names for debugging&lt;br /&gt;  -version                     Print product version and exit&lt;br /&gt;  -help                        Print a synopsis of standard options&lt;br /&gt;  -X                           Print a synopsis of advanced options&lt;br /&gt;  @&amp;lt;file&gt;                      A text file containing compiler arguments (options and source files)&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;&lt;div&gt;This will get you the port number. Next, you can compile whatever you like from a remote client like this:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush:plain"&gt;$fsc -server 192.168.1.35:1385 strategy.scala&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;That's it. Cool, eh?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-7509854062279127236?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/7509854062279127236/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/compiling-remotely.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/7509854062279127236'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/7509854062279127236'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/compiling-remotely.html' title='Compiling Remotely'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-5578770161623205088</id><published>2009-06-03T11:39:00.009-03:00</published><updated>2011-08-30T10:53:46.133-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='parser'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='operators'/><category scheme='http://www.blogger.com/atom/ns#' term='language'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Parser Surprise</title><content type='html'>&lt;a href="http://www.gracelessfailures.com/2009/05/parser-surprise.html"&gt;David Vydra&lt;/a&gt; found it surprising that he couldn't do the following:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala; gutter: false"&gt;scala&amp;gt; -1.toString&lt;br /&gt;&lt;console&gt;:1: error: ';' expected but '.' found.&lt;br /&gt;-1.toString&lt;br /&gt;^&lt;br /&gt;&lt;/console&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I was surprised too by some similar example, from page 208 of &lt;a href="http://www.amazon.com/gp/product/0981531601?ie=UTF8&amp;amp;tag=algorihmchall-20&amp;amp;linkCode=as2&amp;amp;camp=1789&amp;amp;creative=9325&amp;amp;creativeASIN=0981531601"&gt;Programming in Scala: A Comprehensive Step-by-step Guide&lt;/a&gt;&lt;img alt="" border="0" height="1" src="http://www.assoc-amazon.com/e/ir?t=algorihmchall-20&amp;amp;l=as2&amp;amp;o=1&amp;amp;a=0981531601" style="border: none !important; margin: 0px !important;" width="1" /&gt;.&lt;br /&gt;&lt;br /&gt;Given that example, I would not expect that message in particular, but I would expect an error: that "unary_-" is not a member of java.lang.String, like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala; gutter: false"&gt;scala&amp;gt; -(1 toString)&lt;br /&gt;&lt;console&gt;:5: error: value unary_- is not a member of java.lang.String&lt;br /&gt;-(1 toString)&lt;br /&gt;^&lt;br /&gt;&lt;/console&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Or, in fact, like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala; gutter: false"&gt;scala&amp;gt; +1.toString&lt;br /&gt;&lt;console&gt;:5: error: value unary_+ is not a member of java.lang.String&lt;br /&gt;+1.toString&lt;br /&gt;^&lt;br /&gt;&lt;/console&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Some people have raised the question of operator precedence, claiming "-" ought to have more precedence than ".". It might seems reasonable in this example, where "1" is obviously an integer literal. But what about "-object.size"? Would you expect it to negate the object's size, or to negate the object and then return the size?&lt;br /&gt;&lt;br /&gt;So let's take a look at Scala's operator precedence rule. The rules states that, with a sole excetion, the precedence, from the lowest to the highest, is based on an operator's first character as follow:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;(all letters)&lt;br /&gt;|&lt;br /&gt;^&lt;br /&gt;&amp;amp;&lt;br /&gt;&amp;lt; &amp;gt;&lt;br /&gt;= !&lt;br /&gt;:&lt;br /&gt;+ -&lt;br /&gt;* / &amp;amp;&lt;br /&gt;(all other special characters)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The exception is that an assignment has lower precedence than any other operator. Because of this excection, += -- an assignment -- has lower precedence than &amp;lt;=, the less-than-or-equal-to operator, even though operators starting with + have precedence over those starting with "&amp;lt;".&lt;br /&gt;&lt;br /&gt;These, though, are the precedence rules for &lt;i&gt;infix&lt;/i&gt; operators, and "-" in "-1" is not infix, but prefix. So, does infix precedence applies for prefix operators? No, as the example below shows:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala; gutter: false"&gt;scala&amp;gt; class X {&lt;br /&gt;| def unary_- = {println("Unary -"); this}&lt;br /&gt;| def *(b : X) = {println("operator *"); this}&lt;br /&gt;| def -(b : X) = {println("operator -"); this}&lt;br /&gt;| override def toString = "class X"&lt;br /&gt;| }&lt;br /&gt;defined class X&lt;br /&gt;&lt;br /&gt;scala&amp;gt; new X&lt;br /&gt;res16: X = class X&lt;br /&gt;&lt;br /&gt;scala&amp;gt; new X&lt;br /&gt;res17: X = class X&lt;br /&gt;&lt;br /&gt;scala&amp;gt; -res16 * res17&lt;br /&gt;Unary -&lt;br /&gt;operator *&lt;br /&gt;res18: X = class X&lt;br /&gt;&lt;br /&gt;scala&amp;gt; res16 - res17 * res16&lt;br /&gt;operator *&lt;br /&gt;operator -&lt;br /&gt;res19: X = class X&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;So we can see clearly that unary_- has precence over "*", which, itself, has precedence over "-".&lt;br /&gt;&lt;br /&gt;So, back to ".", what is happening? Well, for one thing, &lt;i&gt;"." is not an operator&lt;/i&gt;. Dot is considered an operator in some other languages. In Scala, though, it is a syntactic construct. If it were an operator, you would be able to define it in a class. As it is, it's a reserved symbol. So any operator will only be considered after resolving ".".&lt;br /&gt;&lt;br /&gt;Still, again, why isn't the error as follow?&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala; gutter: false"&gt;scala&amp;gt; -(1 toString)&lt;br /&gt;&lt;console&gt;:5: error: value unary_- is not a member of java.lang.String&lt;br /&gt;-(1 toString)&lt;br /&gt;^&lt;br /&gt;&lt;/console&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Johannes Rudolph has since investigated this further. Here is his analysis:&lt;br /&gt;&lt;br /&gt;&lt;div&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;&lt;/span&gt;&lt;br /&gt;&lt;blockquote&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;Originally(*), and despite of the language specification (**),&lt;/span&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;negative number literals could not appear in a select expression&lt;/span&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;(-1.max(5)). Since [19950] which 'fixed' #2378 (***), the balance&lt;/span&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;between integer and floating point literals drifted: for with what the&lt;/span&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;parser was concerned, negative floating point literals received no&lt;/span&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;special treating any more, so -5f.max(2) was seen as&lt;/span&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;(5f.max(2)).unary_-, simple negative floating literals as 5f.unary_-&lt;/span&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;(*!*). For negative integer literals the situation stayed the way it&lt;/span&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;was the way before: -1.max(5) was simply not allowed by the parser.&lt;/span&gt;&lt;/blockquote&gt;&lt;blockquote&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;(*) That's [3930], the commit with the unimpressive empty log message&lt;/span&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;where nsc sprang to life.&lt;/span&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;(**) The SLS would allow both 5.unary_- and the literal -5 and does at&lt;/span&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;least not specify how to resolve this ambiguity.&lt;/span&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;(***) The real cause of #2378 can be found in the backyard of the&lt;/span&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;backend: FJBG generates a DCONST_0 if a double literal == 0.0, what&lt;/span&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;-0.0 is.&lt;/span&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;(*!*) This behaviour caused #3486, where negative constants in&lt;/span&gt;&lt;br /&gt;&lt;span class="Apple-style-span" style="border-collapse: collapse; font-family: arial,sans-serif; font-size: 13px;"&gt;annotations wouldn't be possible any more.&lt;/span&gt;&lt;/blockquote&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-5578770161623205088?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/5578770161623205088/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/parser-surprise.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/5578770161623205088'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/5578770161623205088'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/parser-surprise.html' title='Parser Surprise'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-1954325635003592683</id><published>2009-06-02T12:54:00.015-03:00</published><updated>2009-12-09T12:40:25.497-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='scalable-series'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='language'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Scalable Algorithms 2</title><content type='html'>In my &lt;a href="http://dcsobral.blogspot.com/2009/06/scalable-solutions.html"&gt;last post&lt;/a&gt;, I told of a programming challenge taken, and my first go at it. While the algorithm I came up with had a certain cleverness, there was much to criticize about it.&lt;br /&gt;&lt;br /&gt;Another friend, who had received the same challenge, attacked the problem from a different perspective. His algorithm was not as liberal with the input as mine, as it  accepted only abbreviations or single words. It would match a prefix of a word other than the first one, though, which is something mine didn't.&lt;br /&gt;&lt;br /&gt;For instance, if there was an option "create application shortcuts", it would match that against "cas" or any prefix of it (eg. "ca"), "create" or any prefix of it, "application" or any prefix of it and "shortcuts" or any prefix of it.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span" style=""&gt;&lt;span class="Apple-style-span"  style="font-family:verdana;"&gt;&lt;span class="Apple-style-span" style="font-weight: bold;"&gt;Map of Prefixes&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;I won't post his algorithm of it here (though I'd be happy to link to a post of his, if he does so), but the idea was precomputing a couple of maps: one of full abbreviations into set of menu options, and one of words into set of menu options.&lt;br /&gt;&lt;br /&gt;The cleverness of it, though, is that he did not precompute all possible prefixes. Instead, he used ranges, close-ended at the input being matched, and open ended at the input being matched with the last character replaced by it's successor, and applied that range to the keys of each map. The result was that all keys to which the input was a prefix of would be selected.&lt;br /&gt;&lt;br /&gt;Now, there were two things about his algorithm I didn't like. First, it would use mutable sets and maps when precomputing. I was trying to avoid that. Second, it would not match a concatenation of the prefix of different words, so appshort would match the example previously given.&lt;br /&gt;&lt;br /&gt;So I decided to take a shot at it, which, sadly, did not benefit from the range cleverness. As before, I'll follow the code with my criticisms of it.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala; gutter: false"&gt;&lt;br /&gt;val wordsep = "[ :,;]"&lt;br /&gt;def words(s : String) = s.split(wordsep)&lt;br /&gt;def wordPrefixes(s : String) = (0 to s.length).map(s.substring(0,_))&lt;br /&gt;def combinedPrefixes(s : String) =&lt;br /&gt;  words(s).foldLeft(Set(""))((set, word) =&amp;gt;&lt;br /&gt;    set.flatMap(x =&gt; wordPrefixes(word).map(y =&gt; x + y)))&lt;br /&gt;&lt;br /&gt;def reversePhraseMap(l : List[String]) =&lt;br /&gt;  l.foldLeft(Map[String,Set[String]]())((map, phrase) =&amp;gt;&lt;br /&gt;    map + (phrase -&gt; combinedPrefixes(phrase)))&lt;br /&gt;&lt;br /&gt;def allPrefixes(m : Map[String,Set[String]]) = m.values.reduceLeft(_ ++ _)&lt;br /&gt;&lt;br /&gt;def phraseMap(m : Map[String,Set[String]]) =&lt;br /&gt;  Map[String,Set[String]]() ++ allPrefixes(m).&lt;br /&gt;  map(p =&amp;gt; p -&gt; m.foldLeft(Set[String]())((s, x) =&amp;gt;&lt;br /&gt;    if(x._2.contains(p)) s + x._1 else s))&lt;br /&gt;&lt;br /&gt;def indexPhrases(l : List[String]) = phraseMap(reversePhraseMap(l))&lt;br /&gt;&lt;br /&gt;def searchPhrases(l : List[String]) = {&lt;br /&gt;  val index = indexPhrases(l.map(_.toLowerCase))&lt;br /&gt;  (s : String) =&gt; index(s.toLowerCase)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The way you use it is you pass a list of menu options to searchPhrases, and searchPhrases returns a function which will look up an input in the list and return the result.&lt;br /&gt;&lt;br /&gt;Well. I'm not particularly fond of this algorithm, but the code is much more obvious, in my opinion, than the first one. I had to compute the reversed map first (ie, the menu options pointing to a set of their abbreviations), and then reverse that. I wonder if I shouldn't have reversed the definitions name, though (pun half-intended).&lt;br /&gt;&lt;br /&gt;Now, this code is 19 lines vs the first's 34, but this isn't really enough of a difference when considers code complexity. But the first code had 4 "if" statements, all of them followed by "else" statements, one "match" statement and, to boot, a couple of mutually recursive functions. This one has a single "if". This is functional programming at it's best (well, almost best :). In fact, the whole code could be written as a single expression, a single statement:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala; gutter: false"&gt;&lt;br /&gt;def searchPhrases(l : List[String]) = &lt;br /&gt;  (s : String) =&gt; (&lt;br /&gt;    Map[String,Set[String]]() ++ &lt;br /&gt;    (&lt;br /&gt;      (&lt;br /&gt;        l&lt;br /&gt;        map (_ toLowerCase)&lt;br /&gt;        foldLeft Map[String,Set[String]]()&lt;br /&gt;      ) ((map, phrase) =&gt;&lt;br /&gt;        map + (phrase -&gt; &lt;br /&gt;          (&lt;br /&gt;            (&lt;br /&gt;              phrase &lt;br /&gt;              split "[ :,;]"&lt;br /&gt;              foldLeft Set("")&lt;br /&gt;            ) ((set, word) =&gt;&lt;br /&gt;              set flatMap (x =&gt; (&lt;br /&gt;                  0&lt;br /&gt;                  to word.length&lt;br /&gt;                  map (word substring (0, _))&lt;br /&gt;                  map (x + _)&lt;br /&gt;                )&lt;br /&gt;              )&lt;br /&gt;            )&lt;br /&gt;          )&lt;br /&gt;        )&lt;br /&gt;      ).values&lt;br /&gt;      reduceLeft (_ ++ _)&lt;br /&gt;      map (p =&gt; &lt;br /&gt;        p -&gt; (&lt;br /&gt;          (&lt;br /&gt;            (&lt;br /&gt;              (&lt;br /&gt;                l&lt;br /&gt;                map (_.toLowerCase)&lt;br /&gt;                foldLeft Map[String,Set[String]]()&lt;br /&gt;              ) ((map, phrase) =&gt;&lt;br /&gt;                map + &lt;br /&gt;                (phrase -&gt; (&lt;br /&gt;                  (&lt;br /&gt;                    phrase&lt;br /&gt;                    split ("[ :,;]")&lt;br /&gt;                    foldLeft Set("")&lt;br /&gt;                  ) ((set, word) =&gt;&lt;br /&gt;                    (&lt;br /&gt;                      set&lt;br /&gt;                      flatMap (x =&gt; &lt;br /&gt;                        (&lt;br /&gt;                          0 &lt;br /&gt;                          to word.length&lt;br /&gt;                          map (word substring (0, _)) &lt;br /&gt;                          map (x + _)&lt;br /&gt;                        )&lt;br /&gt;                      )&lt;br /&gt;                    )&lt;br /&gt;                  )&lt;br /&gt;                ))&lt;br /&gt;              )&lt;br /&gt;            )&lt;br /&gt;            foldLeft Set[String]()&lt;br /&gt;          ) ((s, x) =&gt;&lt;br /&gt;            if (x._2 contains p) s + x._1 else s&lt;br /&gt;          )&lt;br /&gt;        )&lt;br /&gt;      )&lt;br /&gt;    )&lt;br /&gt;  ) (s toLowerCase)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now, that's a long, long expression to keep track of, and there's some repetition in it. Broken up in smaller definition helps manage the size, and the definition's names help understand what is being done.&lt;br /&gt;&lt;br /&gt;Still, the fact the lack of control structures helps one to focus on what is being done. You don't have to keep backtracking the code and thinking what happens on that other condition. So, while both algorithms deal in immutable objects only, the more you keep to high order functions in place of control structures, the clearer becomes the code.&lt;br /&gt;&lt;br /&gt;This algorithm has a fast search, and it can catch any variation of prefixes, as long as no words are inverted. To do that it spends some time building the map, and the map itself is very wasteful of memory. It doesn't make take advantage of character-by-character input, but it doesn't really need it. It has no heuristics to order the list of matched menu options, though, and no easy way to retrofit it. That I can see, at least.&lt;br /&gt;&lt;br /&gt;At this point, I decided that what I wanted was a DFA matcher, but this took me to an unexpected place first. The next algorithm has 9 lines of code, two being def lines without code, one being a constant definition, and one being "}". At that, it matches everything this algorithm does. Can you beat that before my next post? :-)&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-1954325635003592683?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/1954325635003592683/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/scalable-algorithms-2.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/1954325635003592683'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/1954325635003592683'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/scalable-algorithms-2.html' title='Scalable Algorithms 2'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-6114082217775279863</id><published>2009-06-01T14:12:00.011-03:00</published><updated>2009-12-09T12:39:41.335-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='scalable-series'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='language'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Scalable Algorithms</title><content type='html'>It's common knowledge that the best way of learning a new language is writing a program you wanted in it. Or, perhaps I should say, that's the quickest way of learning a language -- you should beware of the gaps in knowledge of the language that can result from this approach.&lt;br /&gt;&lt;br /&gt;Well, I was trying to do that with Scala, but I always stopped because there was something more I wanted to learn before continuing with one project or other. It was then that a friend posed a challenge, and that finally broke the programmer's block I was having.&lt;br /&gt;&lt;br /&gt;He has written a small program -- in Scala -- with few but loyal followers to help in his gaming sessions, and he wanted something to help with fast keyboard selection. His idea was having an algorithm that would search available menu options based on a few input characters, which would typically stand for an abbreviation of that menu.&lt;br /&gt;&lt;br /&gt;As I took the challenge, I formally specified the algorithm requirement to the following: given a list of phrases (representing menu options) and a string of characters (representing user input), select all phrases for which exists a combination of prefixes of arbitrary length whose concatenation equals the string of characters.&lt;br /&gt;&lt;br /&gt;Preferably, order the result too using some kind of heuristics.&lt;br /&gt;&lt;br /&gt;Well, I wound up writing many solutions to the problem. Of course, there are MANY solutions to the problem -- my friend himself wrote something completely different from any of mine. But I discovered real joy in programming with Scala as I wrote them. So, let me share them with you.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;&lt;span style="font-family:verdana;"&gt;List decomposition&lt;/span&gt;&lt;br /&gt;&lt;/strong&gt;&lt;br /&gt;The first concept I came up with was essentially based on lists. Scala has brought me back with full force to the lists algorithms I used once with functional languages.&lt;br /&gt;&lt;br /&gt;I'll follow the code with my own thoughts about it. But, first, I want to explain the basic concept. First, I transform each phrase into a list of words, each word being a list of characters. The user input also gets transformed into a list of characters. Next, for each phrase I try possible matches against the input, and return a score.&lt;br /&gt;&lt;br /&gt;This is where it gets recursive. After matching each character to the first character of the first word in the list, I select the better of the next two possible options: matching the next character in the word, or the first character in the next word.&lt;br /&gt;&lt;br /&gt;The heuristics I used here gives preference first for matches that consume the whole input, and, next, to matches that match most of the words in the input. As such, and keeping in mind abbreviations are the most likely input, I use a function which receives the recursion as by name parameters, and only computes the second option if the first one doesn't return a perfect match (all input consumed, no words left unmatched).&lt;br /&gt;&lt;br /&gt;Different from the algorithms wrote next, you can't skip words when matching. Also note I severely shortened the comments, as they got a bit too lengthy for a blog.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala; gutter: false"&gt;&lt;br /&gt;// Given two tuples formed by the length of unmatched input and&lt;br /&gt;// the number of unmatched words, choose the "best" of them.&lt;br /&gt;def isBetterThan(a: (Int, Int), b: (Int, Int)) : Boolean = if (a._1 == b._1) {&lt;br /&gt; if (a._2 &amp;lt; b._2) true else false&lt;br /&gt;} else {&lt;br /&gt;  if (a._1 &amp;lt; b._1) true else false&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// Receives two expressions by nam, who, in turn, return a tuple representing&lt;br /&gt;// matching efficacy. Evaluates the first expression and, if the efficacy is&lt;br /&gt;// not the best possible, evaluates the second expression and return the better&lt;br /&gt;// one.&lt;br /&gt;def bestOf(aL: =&amp;gt; (Int, Int), bL : =&amp;gt; (Int, Int)) : (Int, Int) = {&lt;br /&gt; val a = aL&lt;br /&gt; if( a == (0,0)) a&lt;br /&gt; else {&lt;br /&gt;   val b = bL&lt;br /&gt;   if (isBetterThan(a, b)) a else b&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// Try to match the first character of input and menu option. Recurse if&lt;br /&gt;// succesful.&lt;br /&gt;def matchInputToOption(input : List[Char], op : List[List[Char]]) : (Int, Int) = {&lt;br /&gt; (input, op) match {&lt;br /&gt;   case (in1 :: Nil, (op11 :: op1s) :: ops) if (in1 == op11) =&gt;&lt;br /&gt;     (0, ops.length)&lt;br /&gt;   case (in1 :: ins, (op11 :: op1s) :: ops) if (in1 == op11) =&gt;&lt;br /&gt;     bestOf(matchInputToOption(ins, ops),&lt;br /&gt;     matchInputToOption(ins, op1s :: ops))&lt;br /&gt;   case (_, _) =&gt;&lt;br /&gt;     (input.length, op.length)&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// Listify inputs, zip menu options with computed matches, filter for&lt;br /&gt;// matches which consume the whole input, sort them, return.&lt;br /&gt;def searchOptions(input : String, menu : List[String]) : List[(String, Int)] = {&lt;br /&gt; val inputList = input.toList&lt;br /&gt; val menuList = menu.map(_.split(" ").toList.map(_.toList))&lt;br /&gt;&lt;br /&gt; (menu&lt;br /&gt;   zip (menuList map (menuOp =&gt; matchInputToOption(inputList, menuOp)))&lt;br /&gt;   filter (_._2._1 == 0)&lt;br /&gt;   sort ((a,b) =&gt; isBetterThan(a._2,b._2))&lt;br /&gt;   map (x =&gt; (x._1, x._2._2))&lt;br /&gt; )&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-family:Courier New;"&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;This algorithm was born of matchInputToOption. I was charmed by the flexibility of match, and thinking myself oh-so-clever by realizing I could call tail on the list of words or the list of characters of the head of list of words as the only two alternatives after each match. All the rest as created to make this function work.&lt;br /&gt;&lt;br /&gt;I do think that function is clever, and it does go to show Scala's power. The algorithm, itself, can go directly to the nearest trash can. It is easy to check it's correctness -- and please note it only works with immutable objects -- but that isn't enough to make up for its many failings.&lt;br /&gt;&lt;br /&gt;First, I do not precompute anything, and I do require some work transforming all those strings into lists. If Scala is using projections to do it, it might not be all that bad though.&lt;br /&gt;&lt;br /&gt;Next, it has no memory of previous matches. Each time it's called, it matches the whole input. If you happen to feed it character by character, this becomes very wasteful.&lt;br /&gt;&lt;br /&gt;Memory-wise... well, that depends on that projection thingy. If split and toList are being strict (precomputing everything), then we have lists of characters, which are very wasteful.&lt;br /&gt;&lt;br /&gt;It is rather fast, but there are faster ones.&lt;br /&gt;&lt;br /&gt;And, finally, it's not particularly pretty to look at or easy to understand.&lt;br /&gt;&lt;br /&gt;In my next post I'll show a truly memory wasteful algorithm, but a very quick one.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-6114082217775279863?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/6114082217775279863/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/06/scalable-solutions.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/6114082217775279863'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/6114082217775279863'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/06/scalable-solutions.html' title='Scalable Algorithms'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-6866573553261688879</id><published>2009-05-28T21:06:00.012-03:00</published><updated>2009-05-28T23:43:24.585-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='projection'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>Scala's Projections</title><content type='html'>&lt;div&gt;While reading a &lt;a href="http://blogs.msdn.com/chrsmith/archive/2008/04/15/project-euler-problem-34.aspx"&gt;cool posting&lt;/a&gt; by Chris Smith regarding F#, I noticed something he did not remark on, which is very common in functional programming languages. In his code, he makes a sequence from 3 to 3,628,800, and then does a lot of stuff on it. He transforms everything into strings, computes stuff from that string, etc. Here's a Scala equivalent:&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush: scala; gutter: false"&gt;object Factorial {&lt;br /&gt;  private [Factorial] class Fact(n : Int) {&lt;br /&gt;    def ! : Int = if (n &lt;= 1) 1 else (n * new Fact(n-1).!)&lt;br /&gt;  }&lt;br /&gt;  implicit def toFact(n : Int) : Fact = new Fact(n)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;import Factorial._&lt;br /&gt;&lt;br /&gt;println((3 to (10!))&lt;br /&gt;  map (n =&gt; (n, (n.toString&lt;br /&gt;    map (_ asDigit)&lt;br /&gt;    map (_ !)&lt;br /&gt;    reduceLeft (_+_))))&lt;br /&gt;  map (p =&gt; (p._1, p._1 == p._2))&lt;br /&gt;  filter (_._2)&lt;br /&gt;  map (_._1)&lt;br /&gt;  reduceLeft (_+_)&lt;br /&gt;)&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Go ahead, open an interpreter and try it. The factorial stuff was just for fun -- a simpler definition would work more efficiently, in fact. Now, type the following:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala; gutter: false"&gt;(3 to 3628800).toList&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Depending on your Java memory settings, you'll get an Out of Memory error. That's just too much data to store! So, how come you can not only generate that&lt;span class="Apple-style-span" style="font-size: x-small;"&gt;(*)&lt;/span&gt;, but actually do a bunch of stuff on it?&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This magic happens because those map and filter functions are &lt;span class="Apple-style-span" style="font-style: italic;"&gt;non-strict&lt;/span&gt;. A &lt;span class="Apple-style-span" style="font-style: italic;"&gt;strict&lt;/span&gt; function will compute every value and return its result. A &lt;span class="Apple-style-span" style="font-style: italic;"&gt;non-strict&lt;/span&gt; function will return immediately, and each value will only be computed on demand.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;As it happens, you are probably familiar with this concept at another level. Take, for instance, the following two declarations:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala; gutter: false"&gt;val ex1 = 2 + 3&lt;br /&gt;def ex2 = { 2 + 3 }&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;It must be obvious that ex1 == ex2. It should be clear, too, that "2 + 3" was evaluated &lt;span class="Apple-style-span" style="font-style: italic;"&gt;before&lt;/span&gt; its assignment to ex1, but that, in ex2's case, it only gets evaluated when you use ex2 somewhere (like in "ex1 == ex2"). In Scala, another variation exists:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala; gutter: false"&gt;lazy val ex3 = 2 + 3&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;With that declaration, ex3 will only be evaluated when you use it. For example, when the interpreter calls toString on it to display its result. But try this:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala; gutter: false"&gt;lazy val ex3 = { println("here!"); 2 + 3 }; println("Not there yet")&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;You'll see that the second println statement is executed before the first one. Only afterwards, when the interpreter calls toString, is the first one executed. For many, if not most, functional languages, that's how ALL expressions work: lazily.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Anyway, back to ex2, please note that ex2 is a strict function, because it computes "2 + 3" before it returns that value. Then again, there isn't really anything you can do with an Integer that does not require evaluation. But think about a List. You do not need to compute the whole list just to call an isEmpty method on it, for instance. Just the head will do.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;This is what happens in our example. The expression "3 to (10!)" generates a &lt;span class="Apple-style-span" style="font-style: italic;"&gt;R&lt;/span&gt;&lt;span class="Apple-style-span" style="font-style: italic;"&gt;ange&lt;/span&gt;. If you look up Scala's Library documentation on the class Range you'll see that it inherits from &lt;span class="Apple-style-span" style="font-style: italic;"&gt;Projection&lt;/span&gt;, and that Projection has a few "non-strict" methods, and that they return Projections too. Among them are &lt;span class="Apple-style-span" style="font-style: italic;"&gt;map&lt;/span&gt; and &lt;span class="Apple-style-span" style="font-style: italic;"&gt;filter&lt;/span&gt;, the very same methods I'm using in most of that code.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The method &lt;span class="Apple-style-span" style="font-style: italic;"&gt;reduceLeft&lt;/span&gt;, though, is strict. So, what happens is this:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;ol&gt;&lt;li&gt;reduceLeft gets the "head" of the projection it receives, forcing &lt;span class="Apple-style-span"  style="font-size:medium;"&gt;map (_._1) to compute it&lt;/span&gt;&lt;/li&gt;&lt;li&gt;map gets its value from filter (_._2)&lt;/li&gt;&lt;li&gt;filter now starts iterating on the projection it received from the map above it, searching for the first value satisfying its predicate.&lt;/li&gt;&lt;li&gt;as each element tested by filter, both maps above it, and the range itself, compute the next value&lt;/li&gt;&lt;li&gt;after filter finds its first element, it delivers it, and it goes all the way back to reduceLeft&lt;/li&gt;&lt;li&gt;reduceLeft checks if the tail of the projection it received is empty&lt;/li&gt;&lt;li&gt;and that forces all the maps and filters to act again&lt;/li&gt;&lt;/ol&gt;Now, as soon as each element gets consumed by reduceLeft, they get disposed by the garbage collector, because they won't be used anymore. The elements still to be consumed haven't been computed yet, so they don't take any memory either. The only elements taking space in memory are the ones in the act of being processed. And, of course, the data structures used by the projection to make its magic possible.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Compare that to this code:&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;pre class="brush: scala; gutter: false"&gt;println((3 to (10!)).force&lt;br /&gt;  map (n =&gt; (n, (n.toString&lt;br /&gt;    map (_ asDigit)&lt;br /&gt;    map (_ !)&lt;br /&gt;    reduceLeft (_+_))))&lt;br /&gt;  map (p =&gt; (p._1, p._1 == p._2))&lt;br /&gt;  filter (_._2)&lt;br /&gt;  map (_._1)&lt;br /&gt;  reduceLeft (_+_)&lt;br /&gt;)&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Here, we use the method &lt;span class="Apple-style-span" style="font-style: italic;"&gt;force&lt;/span&gt; to get a strict sequence. Even before the first map is executed, a complete sequence of all numbers between 3 and 3,628,800 will be stored in memory. Or, rather, will fill the heap and cause an exception.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;In conclusion, I'd like reinforce that Scala is NOT non-strict by default. It has non-strict collections which can be used within limits. In other functional languages, not even reduceLeft would cause anything to be computed: it would be println causing that. Still, Scala's Projections are powerful tools, which the smart Scala programmer will use wisely to his or her advantage.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;(*) I had originally used "3 to 3628800" instead of "(3 to 3628800).toList", which causes out of memory error on Scala 2.7.4 just fine, but Scala 2.8 is a bit smarter about it, and Range's toString method avoids fully evaluating it, for reasons I hope are now obvious. Thus, I changed the example to something which forces a strict evaluation of the range.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-6866573553261688879?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/6866573553261688879/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/05/scalas-projections.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/6866573553261688879'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/6866573553261688879'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/05/scalas-projections.html' title='Scala&apos;s Projections'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-4832464293982281828</id><published>2009-04-20T02:00:00.017-03:00</published><updated>2009-04-23T01:13:40.855-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='style'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>What does a Scala program looks like?</title><content type='html'>I'm worried. &lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, last Friday, as the daylight slowly disappeared, much in the same way and same rate as the people in the immense building that someone somehow thought was fit to be called a workplace -- and, worse yet, be used as such -- I was engaged in a deep conversation about miscellaneous subjects with a colleague. Or, as someone else might rudely put it, I was chit chatting.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;At some point, the conversation turned to Java, Ruby on Rails, money, and, finally Scala. My colleague was ignorant of the ways of Rails, and I was telling him how mind blowing it was when it came to creating web sites. I mistakenly mentioned to him having seen a weblog being created in just 25 minutes on a screencast (it's actually 15 minutes -- first screencast &lt;a href="http://rubyonrails.org/screencasts"&gt;here&lt;/a&gt;). I urged him to look it up.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Anyway, the conversation briefly turned into Java, and how it came to be because it was basically the only game in town for webapps at the beginning, and how, basically, everything was better than Java. But don't take this too literally -- I &lt;span class="Apple-style-span" style="FONT-STYLE: italic"&gt;was&lt;/span&gt; chit chatting... Anyway, the conversation gave a final turn towards Scala at this point.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;As my colleague was leaving, he asked me if Scala really was that good, whether it was compiled or interpreted, etc. I told him yes, it was that good, compiled, but with an "interpreter" available, that it produced JAR which could be decompiled by cavaj into readable Java, and then invited him into taking a look into a small program I have to check lottery results. &lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;So, this is a small program I did mainly as a learning experiment. I have one written in Perl, which could have been easily ported to Scala, but I was interested into how a Scala programmer might have gone about it. My present solution is rather functional in style, though I'm considering a couple of case classes for it.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;At any rate, I gave a brief overview on some concepts, such as val, def, extending Application, access to Java types and library, explained a few helping functions, and then got to the meat of the program, which I post below.&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;pre class="brush: scala; gutter: false"&gt;&lt;br /&gt;val prizes = lines.&lt;br /&gt;    dropWhile(!_.startsWith("1 ")).              // Remove header&lt;br /&gt;    map(_.stripLineEnd.split(" ")).              // Tokenize line&lt;br /&gt;    takeWhile(s =&gt; isInt(s(0))).                 // Remove trailer&lt;br /&gt;    map(s =&gt; readGame(s)).                       // Turn list into tuple&lt;br /&gt;    map(s =&gt; (s, ticketPrizes(s._3, tickets))).  // Compute winning tickets&lt;br /&gt;    filter(s =&gt; s._2.size &gt; 0)                   // Remove losing games&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt; &lt;/div&gt;&lt;div&gt; &lt;/div&gt;&lt;div&gt; &lt;/div&gt;&lt;div&gt; &lt;/div&gt;&lt;div&gt;There's actually a lot of stuff going on there, but the point of that code was figuring out what an elegant Scala program might look like. Now, it does take advantage of some of Scala's power, but there's a lot it &lt;span class="Apple-style-span" style="FONT-STYLE: italic"&gt;doesn't&lt;/span&gt; take advantage of. In particular, it doesn't take advantage of anything in Scala's type system or class system.&lt;/div&gt;&lt;div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;With that in mind, I started to tell my colleague this was written in a functional style, but you can have OO style as well. Before I finished, though, he inquired about Scala's usual style. Which, finally, led to my present worry.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;I do not claim to have seen tons of Scala code, but I have been reading pretty much any blog posting about Scala and I haven't seen any common style.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now, when Java came to be, some effort went into defining the style a proper Java program ought to be written in. I do claim to have seen a lot of Java code, both ugly and elegant, and all of it looked &lt;span class="Apple-style-span" style="FONT-STYLE: italic"&gt;the same.&lt;/span&gt; Whenever a beginner broke with Java style, it came across in stark contrast -- and was a sign of programmer's inexperience.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now, as for Scala, there's really very little emphasis on style being done. In fact, Scala's emphasis on not dictating how to solve a problem seems to be spilling into not dictating a coding style. And, as all of this went through my head in the space of a few seconds (I hope!), I realized something about Java's emphasis on style. It was comforting.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Let's put that thought on hold for a second, while I digress a bit. I have been programming for 26 years now. I started with BASIC, did some assembler (Z-80 mostly, but also 8080 and 6502), then learned Forth, because a FIG member, and then... C, Logo, MUMPS, LISP, APL, and anything I could put my hands on. I don't &lt;span class="Apple-style-span" style="FONT-STYLE: italic"&gt;recall&lt;/span&gt; what languages I have once learned, but every now and then someone will mention an obscure language, such as Oberon, and I'll remember having learned it.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Forth, in particular, is a language whose main intent seems to be modifying the language. Something I did with much gusto. So it's not like I'm a conservative guy when it comes to languages.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Now, back to the comfort of Java's uniform style, the thing is... it's easier on my mind that every piece of Java code I lay my eyes on follows it. And, as I realized that, I was sure as hell that was also the case for the huge mass of average programmers that abound in the Enterprise world. The uniform style makes the code look &lt;span class="Apple-style-span" style="FONT-STYLE: italic"&gt;professional&lt;/span&gt;, no matter how messy it actually is.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;And, then, back to Scala, I answered my friend: "Scala doesn't &lt;span class="Apple-style-span" style="FONT-STYLE: italic"&gt;have&lt;/span&gt; a style right now. It might develop one." Well, actually, it has dozens of style, but you get my drift.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;And this, my friends, worries me. I can't see Scala going mainstream if a consistent style doesn't start showing up. Right now, everyone seems to be playing with it, figuring out what works and what doesn't. Scala is so powerful that people are actively trying to push the envelope, to test its limits in concision and expressiveness. It might take a while for its best practices to develop.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Hopefully, it won't be too late.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6373963829340632529-4832464293982281828?l=dcsobral.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://dcsobral.blogspot.com/feeds/4832464293982281828/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://dcsobral.blogspot.com/2009/04/what-does-scala-program-looks-like.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/4832464293982281828'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6373963829340632529/posts/default/4832464293982281828'/><link rel='alternate' type='text/html' href='http://dcsobral.blogspot.com/2009/04/what-does-scala-program-looks-like.html' title='What does a Scala program looks like?'/><author><name>Daniel Sobral</name><uri>https://profiles.google.com/109369058791340660984</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-kT9Yx3TZ8Ds/AAAAAAAAAAI/AAAAAAAAAfY/7lMPHBqd7Ak/s512-c/photo.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6373963829340632529.post-3985035815219944242</id><published>2009-03-26T20:19:00.004-03:00</published><updated>2009-04-20T03:16:34.454-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='outsourcing'/><category scheme='http://www.blogger.com/atom/ns#' term='software'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><title type='text'>Can it work?</title><content type='html'>As I desperately typed away at the computer, a deadline hanging over my head, I witnessed a strange conversation.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span" style="font-style: italic;"&gt;"Choose five letters,"&lt;/span&gt; my friend was saying. Repeatedly, in fact, as the other guy tried to make sense of this non-sequitur. Now, I can lay back and watch the world go by most of the time, but when I'm in frantic mode and someone is being, well, slow, I get this urge to either slap them senseless or just doing their job for them.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Fortunately for my friend's interlocutor I was typing, not talking on the phone. Unfortunately, for me, my own answer went unheeded. See, my friend was trying to make a point. When he wants to prove something to someone, he tries to engage them in the proof. I sometimes wonder if he realizes this go over the head of most people, who just nod and make sympathetic noises in the hope he will quickly finish his explanation and give the answer they are waiting for. People don't go to restaurants to receive fishing lessons, if you get my drift.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/
