<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Blumenfeld &#38; Maso, Inc. &#187; scala</title>
	<atom:link href="http://www.blumenfeld-maso.com/tag/scala/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.blumenfeld-maso.com</link>
	<description>Cloud, SaaS, and Enterprise Software Design and Development</description>
	<lastBuildDate>Tue, 23 Aug 2011 15:04:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Statically Controlling Calls to Methods in Scala</title>
		<link>http://www.blumenfeld-maso.com/2011/05/statically-controlling-calls-to-methods-in-scala/</link>
		<comments>http://www.blumenfeld-maso.com/2011/05/statically-controlling-calls-to-methods-in-scala/#comments</comments>
		<pubDate>Tue, 03 May 2011 19:48:02 +0000</pubDate>
		<dc:creator>Brian Maso</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[phantom types]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[type classes]]></category>
		<category><![CDATA[type constraints]]></category>

		<guid isPermaLink="false">http://www.blumenfeld-maso.com/?p=197</guid>
		<description><![CDATA[I&#8217;ve recently learned how to use two complimentary static techniques for controlling how many times methods are called in an API: Phantom Types, and Scala type constraints. Why would you want to control the number of times a method is called? Consider, for example, the common Builder Object pattern. I don&#8217;t mean the classic GoF [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve recently learned how to use two complimentary static techniques for controlling how many times methods are called in an API: Phantom Types, and Scala type constraints.</p>
<p>Why would you want to control the number of times a method is called? Consider, for example, the common Builder Object pattern. I don&#8217;t mean the classic GoF Builder Pattern &#8212; I use builders all the time, and I don&#8217;t at all recognize<a href="http://en.wikipedia.org/wiki/Builder_pattern"> this class diagram</a> describing what a Builder is supposed to be. By Builder I mean an object with a fluid API whose job is to collect up state for the purpose of creating one or more other objects, which is pretty common in Java and many Scala DSLs.</p>
<p><a href="http://www.blogger.com/profile/03350776762967743057">Rafael Ferriera</a> wrote <a href="http://blog.rafaelferreira.net/2008/07/type-safe-builder-pattern-in-scala.html">a piece</a> about builders and Phantom Types I&#8217;m going to use as a starting point for introduction of the topic. I&#8217;ll start with his introduction of a <tt>ScotchBuilder</tt>: a Scala object that knows how to take a proper gentleman&#8217;s order for a scotch.</p>
<p>Let me quote Raphael to introduce the domain:</p>
<blockquote><p>So, let&#8217;s say you want to order a shot of scotch. You&#8217;ll need to ask for  a few things: the brand of the whiskey, how it should be prepared  (neat, on the rocks or with water) and if you want it doubled. Unless,  of course, you are a pretentious snob, in that case you&#8217;ll probably also  ask for a specific kind of glass, brand and temperature of the water  and who knows what else. Limiting the snobbery to the kind of glass,  here is one way to represent the order in scala.</p>
<div id="wpshdo_1" class="wp-synhighlighter-outer"><div id="wpshdt_1" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_1"></a><a id="wpshat_1" class="wp-synhighlighter-title" href="#codesyntax_1"  onClick="javascript:wpsh_toggleBlock(1)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_1" onClick="javascript:wpsh_code(1)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_1" onClick="javascript:wpsh_print(1)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_1" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;"><a href="http://scala-lang.org"><span class="kw1">sealed</span></a> <a href="http://scala-lang.org"><span class="kw1">abstract</span></a> <a href="http://scala-lang.org"><span class="kw1">class</span></a> Preparation  <span class="coMULTI">/* This is one way of coding enum-like things in scala */</span>
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">object</span></a> Neat <a href="http://scala-lang.org"><span class="kw1">extends</span></a> Preparation
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">object</span></a> OnTheRocks <a href="http://scala-lang.org"><span class="kw1">extends</span></a> Preparation
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">object</span></a> WithWater <a href="http://scala-lang.org"><span class="kw1">extends</span></a> Preparation
&nbsp;
<a href="http://scala-lang.org"><span class="kw1">sealed</span></a> <a href="http://scala-lang.org"><span class="kw1">abstract</span></a> <a href="http://scala-lang.org"><span class="kw1">class</span></a> Glass
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">object</span></a> Short <a href="http://scala-lang.org"><span class="kw1">extends</span></a> Glass
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">object</span></a> Tall <a href="http://scala-lang.org"><span class="kw1">extends</span></a> Glass
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">object</span></a> Tulip <a href="http://scala-lang.org"><span class="kw1">extends</span></a> Glass
&nbsp;
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">class</span></a> OrderOfScotch<span class="br0">&#40;</span><a href="http://scala-lang.org"><span class="kw1">val</span></a> brand<span class="sy0">:</span>String, <a href="http://scala-lang.org"><span class="kw1">val</span></a> mode<span class="sy0">:</span>Preparation, <a href="http://scala-lang.org"><span class="kw1">val</span></a> isDouble<span class="sy0">:</span>Boolean, <a href="http://scala-lang.org"><span class="kw1">val</span></a> glass<span class="sy0">:</span>Option<span class="br0">&#91;</span>Glass<span class="br0">&#93;</span><span class="br0">&#41;</span></pre></div></div></blockquote>
<p>You can imagine providing a ScotchBuilder class to generate immutable OrderOfScotch objects with a fluid API. Below is a first-pass at such a ScotchBuilder, which is your typical fluid implementation. Its nice, but we can do better. (Code, again, taken originally from Raphael&#8217;s post, modulo changing from stateful to stateless and fixing a couple of his typos)</p>
<div id="wpshdo_2" class="wp-synhighlighter-outer"><div id="wpshdt_2" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_2"></a><a id="wpshat_2" class="wp-synhighlighter-title" href="#codesyntax_2"  onClick="javascript:wpsh_toggleBlock(2)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_2" onClick="javascript:wpsh_code(2)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_2" onClick="javascript:wpsh_print(2)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_2" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;"><a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">class</span></a> ScotchBuilder<span class="br0">&#40;</span>
    theBrand        <span class="sy0">:</span>Option<span class="br0">&#91;</span>String<span class="br0">&#93;</span> <span class="sy0">=</span> None,
    theMode         <span class="sy0">:</span>Option<span class="br0">&#91;</span>Preparation<span class="br0">&#93;</span> <span class="sy0">=</span> None,
    theDoubleStatus <span class="sy0">:</span>Option<span class="br0">&#91;</span>Boolean<span class="br0">&#93;</span> <span class="sy0">=</span> None,
    theGlass        <span class="sy0">:</span>Option<span class="br0">&#91;</span>Glass<span class="br0">&#93;</span> <span class="sy0">=</span> None<span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
  <a href="http://scala-lang.org"><span class="kw1">def</span></a> withBrand<span class="br0">&#40;</span>b<span class="sy0">:</span>String<span class="br0">&#41;</span> <span class="sy0">=</span> copy<span class="br0">&#40;</span>theBrand <span class="sy0">=</span> Some<span class="br0">&#40;</span>b<span class="br0">&#41;</span><span class="br0">&#41;</span>
  <a href="http://scala-lang.org"><span class="kw1">def</span></a> withMode<span class="br0">&#40;</span>p<span class="sy0">:</span>Preparation<span class="br0">&#41;</span> <span class="sy0">=</span> copy<span class="br0">&#40;</span>theMode <span class="sy0">=</span> Some<span class="br0">&#40;</span>p<span class="br0">&#41;</span><span class="br0">&#41;</span>
  <a href="http://scala-lang.org"><span class="kw1">def</span></a> isDouble<span class="br0">&#40;</span>b<span class="sy0">:</span>Boolean<span class="br0">&#41;</span> <span class="sy0">=</span> copy<span class="br0">&#40;</span>theDoubleStatus <span class="sy0">=</span> Some<span class="br0">&#40;</span>b<span class="br0">&#41;</span><span class="br0">&#41;</span>
  <a href="http://scala-lang.org"><span class="kw1">def</span></a> withGlass<span class="br0">&#40;</span>g<span class="sy0">:</span>Glass<span class="br0">&#41;</span> <span class="sy0">=</span> copy<span class="br0">&#40;</span>theGlass <span class="sy0">=</span> Some<span class="br0">&#40;</span>g<span class="br0">&#41;</span><span class="br0">&#41;</span>
&nbsp;
  <a href="http://scala-lang.org"><span class="kw1">def</span></a> build<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">=</span> <a href="http://scala-lang.org"><span class="kw1">new</span></a> OrderOfScotch<span class="br0">&#40;</span>theBrand.<span class="me1">get</span>, theMode.<span class="me1">get</span>, theDoubleStatus.<span class="me1">get</span>, theGlass<span class="br0">&#41;</span><span class="sy0">;</span>
  <span class="br0">&#125;</span></pre></div></div>
<p>There are two unattractive features with this Builder  that we are going to clean up:</p>
<ol>
<li>a client can re-invoke the same setter methods over and over</li>
<li>the client can also completely forget to call other methods that should be called</li>
</ol>
<p>Check this out, where I am able to make a non-sense scotch order:</p>
<div id="wpshdo_3" class="wp-synhighlighter-outer"><div id="wpshdt_3" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_3"></a><a id="wpshat_3" class="wp-synhighlighter-title" href="#codesyntax_3"  onClick="javascript:wpsh_toggleBlock(3)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_3" onClick="javascript:wpsh_code(3)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_3" onClick="javascript:wpsh_print(3)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_3" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;">Welcome to Scala version 2.8.1.<a href="http://scala-lang.org"><span class="kw1">final</span></a> <span class="br0">&#40;</span>Java HotSpot<span class="br0">&#40;</span>TM<span class="br0">&#41;</span> 64-Bit Server VM, Java 1.
6.0<span class="sy0">_</span>21<span class="br0">&#41;</span>.
<span class="me1">Type</span> in expressions to have them evaluated.
<span class="me1">Type</span> <span class="sy0">:</span>help <a href="http://scala-lang.org"><span class="kw1">for</span></a> more information.
&nbsp;
<span class="me1">scala</span><span class="sy0">&gt;</span> <a href="http://scala-lang.org"><span class="kw1">val</span></a> b <span class="sy0">=</span> <a href="http://scala-lang.org"><span class="kw1">new</span></a> ScotchBuilder
b<span class="sy0">:</span> ScotchBuilder <span class="sy0">=</span> ScotchBuilder<span class="sy0">@</span>6f77e5d4
&nbsp;
scala<span class="sy0">&gt;</span> b withBrand <span class="st0">&quot;Cragganmore&quot;</span> withMode Neat isDouble <a href="http://scala-lang.org"><span class="kw1">false</span></a> withBrand <span class="st0">&quot;Macallan 25 year&quot;</span> isDouble <a href="http://scala-lang.org"><span class="kw1">true</span></a> build
res3<span class="sy0">:</span> OrderOfScotch <span class="sy0">=</span> OrderOfScotch<span class="br0">&#40;</span>Macallan 25 year,Neat,<a href="http://scala-lang.org"><span class="kw1">true</span></a>,None<span class="br0">&#41;</span></pre></div></div>
<p>Notice I was able to specify the brand twice, and the size as both &#8220;double&#8221; and &#8220;single&#8221;. Quite ambiguous what I meant there. Considering the price difference between a single Cragganmore (cheap) and a double Macallan 25 (expensive!), that&#8217;s maybe an ambiguity we&#8217;d like to stamp out of the system.</p>
<p>I&#8217;m going to now show you how to use both Phantom Types and type constraints to ensure at compile time certain Builder methods are invoked:</p>
<ul>
<li>with <em>at-most-once</em> semantics. E.g., <tt>withGlass</tt> should be called zero or one time by client code for a single ScotchBuilder instance.</li>
<li>with <em>exactly-once</em> semantics. E.g., <tt>withBrand</tt>, <tt>withMode</tt>, and <tt>isDouble</tt> each need to be called exactly once.</li>
<li>and, by the way, you can use this same technique to define <em>one-or-more-times</em> semantics. (Though I&#8217;m not going to go that far in this article. If you grok at-most-once and exactly-once, you will be able to figure out one-or-more-times.)</li>
</ul>
<p>These techniques are not limited to just fluid Builder APIs. Pretty much any API where you wanted to constraint the call semantics can employ Phantom Types and type constraints to achieve the desired call semantics. This is going to apply to objects that traditionally walk through a lifecycle. For example, any API where there are <tt>init()</tt> and <tt>destroy()</tt>. The Builder under consideration also has a lifecycle: several configuration methods must be called, and then finally the <tt>build</tt> method gets invoked.</p>
<p>Continuing the Builder example, first I&#8217;m going to stop the <tt>build</tt> method from working if there are any builder values that haven&#8217;t been set correctly. That is, using Phantom Types and type constraints, I&#8217;m going to set things up so that compiler won&#8217;t even compile code that attempts to build a scotch when all the builder parameters have not been set. After that I&#8217;m going to stop the individual <tt>withXYZ</tt> methods from being called more than once using the same technique.</p>
<p>Here&#8217;s how I&#8217;m going to do make the <tt>build</tt> method uncallable except when the Builder has been fully configured: I&#8217;m going to add to the <tt>ScotchBuilder</tt> class one type parameter per method whose calls we want to track. The type parameters are going to track whether each of the <tt>withXYZ()</tt> methods have been called or not; the classes <tt>Zero</tt> and <tt>Once</tt> are defined to represent these two states. I&#8217;m then going to constrain the <tt>build</tt> method to only be callable if the appropriate type parameters are bound to the <tt>Once</tt> type.</p>
<p>So I&#8217;m adding 4 type parameters, each able to be bound to the type <tt>Zero</tt> or <tt>Once</tt>. So instead of having 1 <tt>ScotchBuilder</tt> class, I actually am defining 16. That is, 16 different permutations of the possible bindings to the 4 type parameters. The <tt>build</tt> method will then be constraining to be callable on <tt>ScotchBuilder[Once, Once, Once, _]</tt> (one of 2 specific bindings).</p>
<p>This first chunk of code adds the <tt>Zero</tt> and <tt>Once</tt> types to track the number of times the individual <tt>withXYZ()</tt> methods are called below. Note that the case class <tt>copy</tt> method allows you to specify type parameters, which I&#8217;m using in the implementation of each <tt>withXYZ</tt> method:</p>
<div id="wpshdo_4" class="wp-synhighlighter-outer"><div id="wpshdt_4" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_4"></a><a id="wpshat_4" class="wp-synhighlighter-title" href="#codesyntax_4"  onClick="javascript:wpsh_toggleBlock(4)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_4" onClick="javascript:wpsh_code(4)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_4" onClick="javascript:wpsh_print(4)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_4" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;"><a href="http://scala-lang.org"><span class="kw1">abstract</span></a> <a href="http://scala-lang.org"><span class="kw1">sealed</span></a> <a href="http://scala-lang.org"><span class="kw1">class</span></a> Count
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">class</span></a> Zero <a href="http://scala-lang.org"><span class="kw1">extends</span></a> Count
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">class</span></a> Once <a href="http://scala-lang.org"><span class="kw1">extends</span></a> Count
&nbsp;
<a href="http://scala-lang.org"><span class="kw1">object</span></a> ScotchBuilder <span class="br0">&#123;</span>
  <a href="http://scala-lang.org"><span class="kw1">def</span></a> apply<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">=</span> <a href="http://scala-lang.org"><span class="kw1">new</span></a> ScotchBuilder<span class="br0">&#91;</span>Zero, Zero, Zero, Zero<span class="br0">&#93;</span><span class="br0">&#40;</span><span class="br0">&#41;</span>
  <span class="br0">&#125;</span>
&nbsp;
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">class</span></a> ScotchBuilder
    <span class="br0">&#91;</span>WithBrandTracking <span class="sy0">&lt;:</span> Count,
     WithModeTracking <span class="sy0">&lt;:</span> Count,
     IsDoubleTracking <span class="sy0">&lt;:</span>Count,
     WithGlassTracking <span class="sy0">&lt;:</span> Count<span class="br0">&#93;</span> <span class="br0">&#40;</span>
    theBrand        <span class="sy0">:</span>Option<span class="br0">&#91;</span>String<span class="br0">&#93;</span> <span class="sy0">=</span> None,
    theMode         <span class="sy0">:</span>Option<span class="br0">&#91;</span>Preparation<span class="br0">&#93;</span> <span class="sy0">=</span> None,
    theDoubleStatus <span class="sy0">:</span>Option<span class="br0">&#91;</span>Boolean<span class="br0">&#93;</span> <span class="sy0">=</span> None,
    theGlass        <span class="sy0">:</span>Option<span class="br0">&#91;</span>Glass<span class="br0">&#93;</span> <span class="sy0">=</span> None<span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
  <a href="http://scala-lang.org"><span class="kw1">def</span></a> withBrand<span class="br0">&#40;</span>b<span class="sy0">:</span>String<span class="br0">&#41;</span> <span class="sy0">=</span> copy<span class="br0">&#91;</span>Once, WithModeTracking, IsDoubleTracking, WithGlassTracking<span class="br0">&#93;</span><span class="br0">&#40;</span>theBrand <span class="sy0">=</span> Some<span class="br0">&#40;</span>b<span class="br0">&#41;</span><span class="br0">&#41;</span>
  <a href="http://scala-lang.org"><span class="kw1">def</span></a> withMode<span class="br0">&#40;</span>p<span class="sy0">:</span>Preparation<span class="br0">&#41;</span> <span class="sy0">=</span> copy<span class="br0">&#91;</span>WithBrandTracking, Once, IsDoubleTracking, WithGlassTracking<span class="br0">&#93;</span><span class="br0">&#40;</span>theMode <span class="sy0">=</span> Some<span class="br0">&#40;</span>p<span class="br0">&#41;</span><span class="br0">&#41;</span>
  <a href="http://scala-lang.org"><span class="kw1">def</span></a> isDouble<span class="br0">&#40;</span>b<span class="sy0">:</span>Boolean<span class="br0">&#41;</span> <span class="sy0">=</span> copy<span class="br0">&#91;</span>WithBrandTracking, WithModeTracking, Once, WithGlassTracking<span class="br0">&#93;</span><span class="br0">&#40;</span>theDoubleStatus <span class="sy0">=</span> Some<span class="br0">&#40;</span>b<span class="br0">&#41;</span><span class="br0">&#41;</span>
  <a href="http://scala-lang.org"><span class="kw1">def</span></a> withGlass<span class="br0">&#40;</span>g<span class="sy0">:</span>Glass<span class="br0">&#41;</span> <span class="sy0">=</span> copy<span class="br0">&#91;</span>WithBrandTracking, WithModeTracking, IsDoubleTracking, Once<span class="br0">&#93;</span><span class="br0">&#40;</span>theGlass <span class="sy0">=</span> Some<span class="br0">&#40;</span>g<span class="br0">&#41;</span><span class="br0">&#41;</span>
&nbsp;
  <span class="co1">//...build() method definition with appropriate type constraints is just below...</span>
  <span class="br0">&#125;</span></pre></div></div>
<p>And below is the <tt>build</tt> method, with type constraints guaranteeing the <tt>build</tt> method can only be called on instances of type <tt>ScotchBuilder[Once, Once, Once, _]</tt>.</p>
<div id="wpshdo_5" class="wp-synhighlighter-outer"><div id="wpshdt_5" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_5"></a><a id="wpshat_5" class="wp-synhighlighter-title" href="#codesyntax_5"  onClick="javascript:wpsh_toggleBlock(5)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_5" onClick="javascript:wpsh_code(5)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_5" onClick="javascript:wpsh_print(5)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_5" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;"><a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">class</span></a> ScotchBuilder<span class="br0">&#91;</span>...<span class="br0">&#93;</span> <span class="br0">&#123;</span>
  ...
&nbsp;
  <a href="http://scala-lang.org"><span class="kw1">type</span></a> IsOnce<span class="br0">&#91;</span>T<span class="br0">&#93;</span> <span class="sy0">=</span> <span class="sy0">=:=</span><span class="br0">&#91;</span>T, Once<span class="br0">&#93;</span>
&nbsp;
  ...
&nbsp;
  <a href="http://scala-lang.org"><span class="kw1">def</span></a> build<span class="br0">&#91;</span>B <span class="sy0">&lt;:</span> WithBrandTracking <span class="sy0">:</span> IsOnce, M <span class="sy0">&lt;:</span> WithModeTracking <span class="sy0">:</span> IsOnce, D <span class="sy0">&lt;:</span> IsDoubleTracking <span class="sy0">:</span> IsOnce<span class="br0">&#93;</span> <span class="sy0">=</span>
      <a href="http://scala-lang.org"><span class="kw1">new</span></a> OrderOfScotch<span class="br0">&#40;</span>withBrand.<span class="me1">get</span>, withMode.<span class="me1">get</span>, isDoubleStatus.<span class="me1">get</span>, withGlass<span class="br0">&#41;</span>
&nbsp;
  ...
  <span class="br0">&#125;</span></pre></div></div>
<p>I use the <tt>=:=</tt> type class to guarantee this constraint on the  <tt>ScotchBuilder</tt> type parameters. An implicit value of <tt>=:=[A, B]</tt> only exists when <tt>A</tt> ==  <tt>B</tt>. (For a deeper explanation of the <tt>=:=</tt> type constraining object, check  out <a href="http://java.dzone.com/articles/using-generalized-type?utm_source=am6_feedtweet&amp;utm_medium=twitter&amp;utm_campaign=toya256ForRSS">this blog post</a> by Debasish Ghosh). I&#8217;ve further created a type alias <tt>IsOnce[T] = =:=[T, Once]</tt>, which allows me to apply <tt>=:=</tt> as a type class.</p>
<p>The upshot of all of this is that any attempt to invoke build on a <tt>ScotchBuilder</tt> not matching <tt>ScotchBuilder[Once, Once, Once, _]</tt> simply cannot be compiled. You literally cannot compile code that improperly uses a <tt>ScotchBuilder</tt> to build a order of scotch!</p>
<p>Note that in the code above we never actually create an instance of <tt>Zero</tt> or <tt>Once</tt> &#8212; these type parameter bindings are purely for compile-time  bookkeeping. Hence the term Phantom Types, because these types are never  instantiated nor participate at runtime.</p>
<p>We can even do a little better with the builder above by constraining the <tt>withXYZ</tt> methods to have <em>exactly-once</em> or <em>at-most-once</em> call semantics, as appropriate. This is going to make the compiler fail at the point where the API is being misused &#8212; i.e., where a <tt>withXYZ</tt> method is being used the second time for a single <tt>ScotchBuilkder</tt> instance. So it&#8217;ll be a lot easier when using this API to figure out what you did wrong. Here is the final version of <tt>ScotchBuilder</tt>:</p>
<div id="wpshdo_6" class="wp-synhighlighter-outer"><div id="wpshdt_6" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_6"></a><a id="wpshat_6" class="wp-synhighlighter-title" href="#codesyntax_6"  onClick="javascript:wpsh_toggleBlock(6)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_6" onClick="javascript:wpsh_code(6)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_6" onClick="javascript:wpsh_print(6)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_6" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;"><a href="http://scala-lang.org"><span class="kw1">sealed</span></a> <a href="http://scala-lang.org"><span class="kw1">abstract</span></a> <a href="http://scala-lang.org"><span class="kw1">class</span></a> Preparation  <span class="coMULTI">/* This is one way of coding enum-like things in scala */</span>
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">object</span></a> Neat <a href="http://scala-lang.org"><span class="kw1">extends</span></a> Preparation
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">object</span></a> OnTheRocks <a href="http://scala-lang.org"><span class="kw1">extends</span></a> Preparation
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">object</span></a> WithWater <a href="http://scala-lang.org"><span class="kw1">extends</span></a> Preparation
&nbsp;
<a href="http://scala-lang.org"><span class="kw1">sealed</span></a> <a href="http://scala-lang.org"><span class="kw1">abstract</span></a> <a href="http://scala-lang.org"><span class="kw1">class</span></a> Glass
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">object</span></a> Short <a href="http://scala-lang.org"><span class="kw1">extends</span></a> Glass
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">object</span></a> Tall <a href="http://scala-lang.org"><span class="kw1">extends</span></a> Glass
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">object</span></a> Tulip <a href="http://scala-lang.org"><span class="kw1">extends</span></a> Glass
&nbsp;
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">class</span></a> OrderOfScotch<span class="br0">&#40;</span><a href="http://scala-lang.org"><span class="kw1">val</span></a> brand<span class="sy0">:</span>String, <a href="http://scala-lang.org"><span class="kw1">val</span></a> mode<span class="sy0">:</span>Preparation, <a href="http://scala-lang.org"><span class="kw1">val</span></a> isDouble<span class="sy0">:</span>Boolean, <a href="http://scala-lang.org"><span class="kw1">val</span></a> glass<span class="sy0">:</span>Option<span class="br0">&#91;</span>Glass<span class="br0">&#93;</span><span class="br0">&#41;</span>
&nbsp;
<a href="http://scala-lang.org"><span class="kw1">abstract</span></a> <a href="http://scala-lang.org"><span class="kw1">sealed</span></a> <a href="http://scala-lang.org"><span class="kw1">class</span></a> Count
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">class</span></a> Zero <a href="http://scala-lang.org"><span class="kw1">extends</span></a> Count
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">class</span></a> Once <a href="http://scala-lang.org"><span class="kw1">extends</span></a> Count
&nbsp;
<a href="http://scala-lang.org"><span class="kw1">object</span></a> ScotchBuilder <span class="br0">&#123;</span>
  <a href="http://scala-lang.org"><span class="kw1">def</span></a> apply<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">=</span> <a href="http://scala-lang.org"><span class="kw1">new</span></a> ScotchBuilder<span class="br0">&#91;</span>Zero, Zero, Zero, Zero<span class="br0">&#93;</span><span class="br0">&#40;</span><span class="br0">&#41;</span>
  <span class="br0">&#125;</span>
&nbsp;
<a href="http://scala-lang.org"><span class="kw1">case</span></a> <a href="http://scala-lang.org"><span class="kw1">class</span></a> ScotchBuilder
    <span class="br0">&#91;</span>WithBrandTracking <span class="sy0">&lt;:</span> Count,
     WithModeTracking <span class="sy0">&lt;:</span> Count,
     IsDoubleTracking <span class="sy0">&lt;:</span>Count,
     WithGlassTracking <span class="sy0">&lt;:</span> Count<span class="br0">&#93;</span> <span class="br0">&#40;</span>
    theBrand        <span class="sy0">:</span>Option<span class="br0">&#91;</span>String<span class="br0">&#93;</span> <span class="sy0">=</span> None,
    theMode         <span class="sy0">:</span>Option<span class="br0">&#91;</span>Preparation<span class="br0">&#93;</span> <span class="sy0">=</span> None,
    theDoubleStatus <span class="sy0">:</span>Option<span class="br0">&#91;</span>Boolean<span class="br0">&#93;</span> <span class="sy0">=</span> None,
    theGlass        <span class="sy0">:</span>Option<span class="br0">&#91;</span>Glass<span class="br0">&#93;</span> <span class="sy0">=</span> None<span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
  <a href="http://scala-lang.org"><span class="kw1">type</span></a> IsOnce<span class="br0">&#91;</span>T<span class="br0">&#93;</span> <span class="sy0">=</span> <span class="sy0">=:=</span><span class="br0">&#91;</span>T, Once<span class="br0">&#93;</span>
  <a href="http://scala-lang.org"><span class="kw1">type</span></a> IsZero<span class="br0">&#91;</span>T<span class="br0">&#93;</span> <span class="sy0">=</span> <span class="sy0">=:=</span><span class="br0">&#91;</span>T, Zero<span class="br0">&#93;</span>
&nbsp;
  <a href="http://scala-lang.org"><span class="kw1">def</span></a> withBrand<span class="br0">&#91;</span>B <span class="sy0">&lt;:</span> WithBrandTracking <span class="sy0">:</span> IsZero<span class="br0">&#93;</span><span class="br0">&#40;</span>b<span class="sy0">:</span>String<span class="br0">&#41;</span> <span class="sy0">=</span>
      copy<span class="br0">&#91;</span>Once, WithModeTracking, IsDoubleTracking, WithGlassTracking<span class="br0">&#93;</span><span class="br0">&#40;</span>theBrand <span class="sy0">=</span> Some<span class="br0">&#40;</span>b<span class="br0">&#41;</span><span class="br0">&#41;</span>
&nbsp;
  <a href="http://scala-lang.org"><span class="kw1">def</span></a> withMode<span class="br0">&#91;</span>M <span class="sy0">&lt;:</span> WithModeTracking <span class="sy0">:</span> IsZero<span class="br0">&#93;</span><span class="br0">&#40;</span>p<span class="sy0">:</span>Preparation<span class="br0">&#41;</span> <span class="sy0">=</span>
      copy<span class="br0">&#91;</span>WithBrandTracking, Once, IsDoubleTracking, WithGlassTracking<span class="br0">&#93;</span><span class="br0">&#40;</span>theMode <span class="sy0">=</span> Some<span class="br0">&#40;</span>p<span class="br0">&#41;</span><span class="br0">&#41;</span>
&nbsp;
  <a href="http://scala-lang.org"><span class="kw1">def</span></a> isDouble<span class="br0">&#91;</span>D <span class="sy0">&lt;:</span> WithModeTracking <span class="sy0">:</span> IsZero<span class="br0">&#93;</span><span class="br0">&#40;</span>b<span class="sy0">:</span>Boolean<span class="br0">&#41;</span> <span class="sy0">=</span>
      copy<span class="br0">&#91;</span>WithBrandTracking, WithModeTracking, Once, WithGlassTracking<span class="br0">&#93;</span><span class="br0">&#40;</span>theDoubleStatus <span class="sy0">=</span> Some<span class="br0">&#40;</span>b<span class="br0">&#41;</span><span class="br0">&#41;</span>
&nbsp;
  <a href="http://scala-lang.org"><span class="kw1">def</span></a> withGlass<span class="br0">&#91;</span>G <span class="sy0">&lt;:</span> WithGlassTracking <span class="sy0">:</span> IsZero<span class="br0">&#93;</span><span class="br0">&#40;</span>g<span class="sy0">:</span>Glass<span class="br0">&#41;</span> <span class="sy0">=</span>
      copy<span class="br0">&#91;</span>WithBrandTracking, WithModeTracking, IsDoubleTracking, Once<span class="br0">&#93;</span><span class="br0">&#40;</span>theGlass <span class="sy0">=</span> Some<span class="br0">&#40;</span>g<span class="br0">&#41;</span><span class="br0">&#41;</span>
&nbsp;
  <a href="http://scala-lang.org"><span class="kw1">def</span></a> build<span class="br0">&#91;</span>B <span class="sy0">&lt;:</span> WithBrandTracking <span class="sy0">:</span> IsOnce, M <span class="sy0">&lt;:</span> WithModeTracking <span class="sy0">:</span> IsOnce, D <span class="sy0">&lt;:</span> IsDoubleTracking <span class="sy0">:</span> IsOnce<span class="br0">&#93;</span> <span class="sy0">=</span>
      <a href="http://scala-lang.org"><span class="kw1">new</span></a> OrderOfScotch<span class="br0">&#40;</span>withBrand.<span class="me1">get</span>, withMode.<span class="me1">get</span>, isDoubleStatus.<span class="me1">get</span>, withGlass<span class="br0">&#41;</span>
&nbsp;
  <span class="br0">&#125;</span></pre></div></div>
<p>All this extra type bookkeeping is well worth it for me because it means I don&#8217;t have to write a bunch more test code. I never need to worry or test for cases where client is is misusing my <tt>ScotchBuilder</tt>: it simply is not possible to do. And there&#8217;s never a need to write regression tests against a case which is impossible.
<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.blumenfeld-maso.com%2F2011%2F05%2Fstatically-controlling-calls-to-methods-in-scala%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.blumenfeld-maso.com%2F2011%2F05%2Fstatically-controlling-calls-to-methods-in-scala%2F&amp;source=bmaso&amp;style=normal&amp;service=bit.ly&amp;hashtags=phantom+types,scala,type+classes,type+constraints" height="61" width="50" /><br />
			</a>
		</div>
]]></content:encoded>
			<wfw:commentRss>http://www.blumenfeld-maso.com/2011/05/statically-controlling-calls-to-methods-in-scala/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Non-Strict + Zip = Fab Fib!</title>
		<link>http://www.blumenfeld-maso.com/2010/04/non-strict-zip-fab-fib/</link>
		<comments>http://www.blumenfeld-maso.com/2010/04/non-strict-zip-fab-fib/#comments</comments>
		<pubDate>Wed, 07 Apr 2010 14:41:14 +0000</pubDate>
		<dc:creator>Brian Maso</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[non-strict]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[zipper]]></category>

		<guid isPermaLink="false">http://www.blumenfeld-maso.com/?p=163</guid>
		<description><![CDATA[Just reviewed a gem from Programming Scala. Of all the Fibonacci implementations I&#8217;ve seen, my new favorite is below. Its 1 statement long, and there&#8217;s not a recursive function in sight: If you have not seen that zip trick before, follow me on a little explanation. The code defines a Stream &#8212; a non-strict iterable [...]]]></description>
			<content:encoded><![CDATA[<p>Just reviewed a gem from Programming Scala. Of all the Fibonacci implementations I&#8217;ve seen, my new favorite is below. Its 1 statement long, and there&#8217;s not a recursive function in sight:</p>
<div id="wpshdo_7" class="wp-synhighlighter-outer"><div id="wpshdt_7" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_7"></a><a id="wpshat_7" class="wp-synhighlighter-title" href="#codesyntax_7"  onClick="javascript:wpsh_toggleBlock(7)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_7" onClick="javascript:wpsh_code(7)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_7" onClick="javascript:wpsh_print(7)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_7" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;">lazy <a href="http://scala-lang.org"><span class="kw1">val</span></a> fib<span class="sy0">:</span> Stream<span class="br0">&#91;</span>Int<span class="br0">&#93;</span> <span class="sy0">=</span>
 Stream.<span class="me1">cons</span><span class="br0">&#40;</span><span class="nu0">0</span>, Stream.<span class="me1">cons</span><span class="br0">&#40;</span><span class="nu0">1</span>, fib.<span class="me1">zip</span><span class="br0">&#40;</span>fib.<span class="me1">tail</span><span class="br0">&#41;</span>.<span class="me1">map</span><span class="br0">&#40;</span>p <span class="sy0">=&gt;</span> p.<span class="sy0">_</span>1 + p.<span class="sy0">_</span>2<span class="br0">&#41;</span><span class="br0">&#41;</span><span class="br0">&#41;</span></pre></div></div>
<p>If you have not seen that zip trick before, follow me on a little explanation. The code defines a Stream &#8212; a non-strict iterable &#8212; that begins with two literal values &#8220;0&#8243; and &#8220;1&#8243;. The stream then continues the Fibonacci sequence by zipping the sequence to itself. More specifically, to its own tail sequence.</p>
<p>This figure illustrates what the zipper is creating.</p>
<p><a href="http://www.blumenfeld-maso.com/wp-content/uploads/2010/04/Temp-e1270580117379.png"><img class="aligncenter size-full wp-image-166" title="fab zip fib" src="http://www.blumenfeld-maso.com/wp-content/uploads/2010/04/Temp-e1270580117379.png" alt="Zipping a stream to itself to generate Fibonacci sequence" width="525" height="195" /></a></p>
<p>The tail value of the initial sequence is just the sequence starting with the literal value &#8220;1&#8243;. The zipper creates Pairs out of the each member of the sequence pairwise joined with the next member of the sequence.</p>
<p>The first pair is (0, 1).</p>
<p>The second pair is then (1, 0 + 1) = (1, 1).</p>
<p>The third pair is then (1, 1 + 1) = (1, 2).</p>
<p>The forth pair is then (2, 1 + 2) = (2, 3). And so on.</p>
<p>The coolest part is of course the complete lack of apparent recursion. The whole sequence is lazily evaluated, so the Stream takes up little space &#8212; one new Stream object per element in the sequence.</p>
<h3>Generalizing</h3>
<p>We can generalize this stream-zipping technique. When the value of a Stream element <em>n</em> can be calculated from the previous <em>k</em> sequence members, we can use a k-ary version of this technique. That is, if the stream <em>theStream</em> member <em>n</em> can be defined by some function <em>s</em>:</p>
<p>def theSeq(n) = s(theSeq(n-1), theSeq(n-2), &#8230;, theSeq(n-k))</p>
<p>We can define the stream in a single statement thus:</p>
<ul>
<li>Explicitly define the first <em>k-1</em> stream members</li>
<li>For all other members, perform <em>k-1</em> zips to create a Tuple<em>K</em> of the previous <em>k</em> sequence elements.</li>
<li>A single closure then defines the next element from this Tuple.</li>
</ul>
<p>Here, for example, is a rolling average of the last 4 members of a Stream[Double]:</p>
<div id="wpshdo_8" class="wp-synhighlighter-outer"><div id="wpshdt_8" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_8"></a><a id="wpshat_8" class="wp-synhighlighter-title" href="#codesyntax_8"  onClick="javascript:wpsh_toggleBlock(8)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_8" onClick="javascript:wpsh_code(8)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_8" onClick="javascript:wpsh_print(8)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_8" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;"><a href="http://scala-lang.org"><span class="kw1">val</span></a> data<span class="sy0">:</span> Stream<span class="br0">&#91;</span>Double<span class="br0">&#93;</span> <span class="sy0">=</span> ...
<a href="http://scala-lang.org"><span class="kw1">val</span></a> padded<span class="sy0">_</span>data <span class="sy0">=</span> Stream.<span class="me1">fill</span><span class="br0">&#40;</span><span class="nu0">4</span><span class="br0">&#41;</span><span class="br0">&#40;</span><span class="nu0">0.0</span><span class="br0">&#41;</span> ++ data ++ Stream.<span class="me1">fill</span><span class="br0">&#40;</span><span class="nu0">4</span><span class="br0">&#41;</span><span class="br0">&#40;</span><span class="nu0">0.0</span><span class="br0">&#41;</span>
  <span class="co1">// Note: tail padding not a problem even if data is infinite.</span>
&nbsp;
<span class="coMULTI">/* Here's where the stream is joined to itself. Also,
   mapping the (((Int,Int),Int),Int) to (Int,Int,Int,Int)
   for readability. Can't be recursively defined   */</span>
<a href="http://scala-lang.org"><span class="kw1">def</span></a> zip4<span class="br0">&#91;</span>A<span class="br0">&#93;</span><span class="br0">&#40;</span>str<span class="sy0">:</span> Stream<span class="br0">&#91;</span>A<span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy0">:</span> <span class="br0">&#40;</span>A,A,A,A<span class="br0">&#41;</span> <span class="sy0">=</span>
 <span class="br0">&#40;</span>str zip str.<span class="me1">tail</span> zip str.<span class="me1">tail</span>.<span class="me1">tail</span> zip str.<span class="me1">tail</span>.<span class="me1">tail</span>.<span class="me1">tail</span><span class="br0">&#41;</span> map <span class="br0">&#123;</span> p<span class="sy0">=&gt;</span>
     <span class="br0">&#40;</span>p.<span class="sy0">_</span>1.<span class="sy0">_</span>1.<span class="sy0">_</span>1, p.<span class="sy0">_</span>1.<span class="sy0">_</span>1.<span class="sy0">_</span>2, p.<span class="sy0">_</span>1.<span class="sy0">_</span>2, p.<span class="sy0">_</span>2<span class="br0">&#41;</span><span class="br0">&#125;</span>
&nbsp;
<span class="coMULTI">/* Could be recursively defined in terms of
   base type Product */</span>
<a href="http://scala-lang.org"><span class="kw1">def</span></a> avg4<span class="br0">&#40;</span>p<span class="sy0">:</span> <span class="br0">&#40;</span>Double,Double,Double,Double<span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">:</span> Double <span class="sy0">=</span>
 <span class="br0">&#40;</span>p.<span class="sy0">_</span>1, p.<span class="sy0">_</span>2, p.<span class="sy0">_</span>3, p.<span class="sy0">_</span>4<span class="br0">&#41;</span> / <span class="nu0">4</span>
&nbsp;
<span class="coMULTI">/* Finally, generating the rolling-average stream */</span>
lazy <a href="http://scala-lang.org"><span class="kw1">val</span></a> avg<span class="sy0">_</span>rolling<span class="sy0">:</span> Stream<span class="br0">&#91;</span>Double<span class="br0">&#93;</span> <span class="sy0">=</span>
 zip4<span class="br0">&#40;</span>padded<span class="sy0">_</span>data<span class="br0">&#41;</span> map <span class="br0">&#40;</span>avg4<span class="br0">&#41;</span></pre></div></div>
<p>You can use Iterator.sliding(n) to get a similar effect. And that does work on infinite, non-strict streams. Personally, I just though this technique was so cool, and it does have the benefit of strongly-typed tuples. (Iterator.sliding() simple provides more Streams. Try it out if you&#8217;re curious.)
<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.blumenfeld-maso.com%2F2010%2F04%2Fnon-strict-zip-fab-fib%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.blumenfeld-maso.com%2F2010%2F04%2Fnon-strict-zip-fab-fib%2F&amp;source=bmaso&amp;style=normal&amp;service=bit.ly&amp;hashtags=non-strict,scala,zipper" height="61" width="50" /><br />
			</a>
		</div>
]]></content:encoded>
			<wfw:commentRss>http://www.blumenfeld-maso.com/2010/04/non-strict-zip-fab-fib/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>REST-style URIs as Functional Futures</title>
		<link>http://www.blumenfeld-maso.com/2010/03/rest-style-uris-as-functional-futures/</link>
		<comments>http://www.blumenfeld-maso.com/2010/03/rest-style-uris-as-functional-futures/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 17:18:56 +0000</pubDate>
		<dc:creator>Brian Maso</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[futures]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.blumenfeld-maso.com/?p=136</guid>
		<description><![CDATA[I&#8217;m laboring under an extremely waterfall project right now. A client asked for a set of REST-style services, but the client&#8217;s making me write approx. 200 pages of documentation before writing the code. (Most of the documentation could be replaced by a far smaller, and more logically accurate, Operation State Modeling description. But that&#8217;s not [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m laboring under an extremely <a href="http://en.wikipedia.org/wiki/Waterfall_model">waterfall</a> project right now. A client asked for a set of REST-style services, but the client&#8217;s making me write approx. 200 pages of documentation <em>before</em> writing the code.</p>
<p>(Most of the documentation could be replaced by a far smaller, and more logically accurate, <a href="http://www.ibm.com/developerworks/webservices/library/ar-sosmod/index.html?ca=drs-">Operation State Modeling</a> description. But that&#8217;s not what I&#8217;m here to talk about&#8230;)</p>
<p>Writing the REST-style interface, something pretty interesting occurred to me. I&#8217;ll need the casual reader to put on his thinking cap before moving on here, so please do that if you haven&#8217;t already. I&#8217;ll wait&#8230;</p>
<h2>What is a Future?</h2>
<p>Let&#8217;s start with what a <a href="http://www.ps.uni-saarland.de/alice/manual/futures.html"><em>future</em></a> is: To review, as the linked document says, a <em>future</em> is &#8220;&#8230;a place-holder for the undetermined result of a (concurrent) computation&#8230;&#8221;. Let&#8217;s say there&#8217;s a value your program needs, but the computation or retrieval of that value takes a significant amount of time or resources. Instead of synchronizing (waiting) for the value to be computed, you could spin off an asynchronous process to compute/retrieve the value; alternatively, you could leave a placeholder object that only starts the complex computation/retrieval on demand. Either way, your program leaves in place a placeholder object know as a <em>future</em>.</p>
<p>When your program eventually comes back to the future object asking for the value, the the future either a) hands it back immediately if it has a cached copy; or b) the main program synchronizes (blocks) until the background process completes its computation/retrieval.</p>
<p>The object graph produced by Hibernate when you make an object query uses futures to represent unretrieved values. The query result Hibernate produces is an object graph with placeholder Collections representing lazy relationships. The lazy collections initially don&#8217;t have any data in them, but instead have just enough data in them to generate a secondary Hibernate query. When the program tries to access a lazy collection&#8217;s contents, only then does the Collection query a Hibernate entity manager for the collection of related objects it represents. The placeholder Collection objects are thus futures.</p>
<p><a href="http://www.blumenfeld-maso.com/wp-content/uploads/2010/03/Images_for_URL_as_Future_Post-e1268833802120.jpg"><img class="aligncenter size-full wp-image-142" title="Hibernate Lazy Collections as Futures" src="http://www.blumenfeld-maso.com/wp-content/uploads/2010/03/Images_for_URL_as_Future_Post-e1268833802120.jpg" alt="" width="548" height="412" /></a></p>
<h2>URL/URI References as Lazy Futures</h2>
<p>When a REST-style service response contains a link URL/URI reference to another entity, you can think of that link as a kind of future in the same way as a Hibernate lazily populated Collection. One could easily populate a graph of objects from JSON source, replacing URL/URI references with lazy future objects.</p>
<p>In Scala, a Future[X] extends Function1[X], meaning that Future is Function subtype, so you can use a Function1[_] type to represent URL/URI-based references:</p>
<div id="wpshdo_9" class="wp-synhighlighter-outer"><div id="wpshdt_9" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_9"></a><a id="wpshat_9" class="wp-synhighlighter-title" href="#codesyntax_9"  onClick="javascript:wpsh_toggleBlock(9)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_9" onClick="javascript:wpsh_code(9)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_9" onClick="javascript:wpsh_print(9)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_9" class="wp-synhighlighter-inner" style="display: block;"><pre class="pascal" style="font-family:monospace;"><span class="sy0">/**</span>
 <span class="sy0">*</span> Invoice can be deserialized from JSON such as<span class="sy0">:</span>
 <span class="sy0">*</span> <span class="coMULTI">{
 *   id: &quot;XYZ&quot;,
 *   lineItems: &quot;http://somewhere.com/inv/XYZ/lineItems&quot;
 *       //      ^^^ URL; serialized representation of
 *       //          a List[LineItem] future.
 * }</span>
 <span class="sy0">**/</span>
class Invoice<span class="br0">&#40;</span>val id<span class="sy0">:</span> <span class="kw4">String</span><span class="sy0">,</span>
              val lineItems<span class="sy0">:</span> <span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">=</span>&gt; List<span class="br0">&#91;</span>LineItem<span class="br0">&#93;</span><span class="sy0">,</span>
              ...<span class="br0">&#41;</span> <span class="coMULTI">{
  ...
}</span></pre></div></div>
<p><a href="http://www.blumenfeld-maso.com/wp-content/uploads/2010/03/Images_for_URL_as_Future_Post-1-e1268845847894.jpg"><img class="aligncenter size-full wp-image-148" title="REST URL/URI References as Futures" src="http://www.blumenfeld-maso.com/wp-content/uploads/2010/03/Images_for_URL_as_Future_Post-1-e1268845847894.jpg" alt="" width="550" height="412" /></a>
<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.blumenfeld-maso.com%2F2010%2F03%2Frest-style-uris-as-functional-futures%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.blumenfeld-maso.com%2F2010%2F03%2Frest-style-uris-as-functional-futures%2F&amp;source=bmaso&amp;style=normal&amp;service=bit.ly&amp;hashtags=futures,REST,scala" height="61" width="50" /><br />
			</a>
		</div>
]]></content:encoded>
			<wfw:commentRss>http://www.blumenfeld-maso.com/2010/03/rest-style-uris-as-functional-futures/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scala Word of the Day: For Loops (All 4 Kinds!)</title>
		<link>http://www.blumenfeld-maso.com/2010/01/scala-word-of-the-day-for-loops-all-4-kinds/</link>
		<comments>http://www.blumenfeld-maso.com/2010/01/scala-word-of-the-day-for-loops-all-4-kinds/#comments</comments>
		<pubDate>Sat, 23 Jan 2010 06:36:54 +0000</pubDate>
		<dc:creator>Brian Maso</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Scala Word of the Day]]></category>
		<category><![CDATA[for loop]]></category>
		<category><![CDATA[iterable]]></category>
		<category><![CDATA[iterator]]></category>
		<category><![CDATA[non-strict]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.blumenfeld-maso.com/?p=90</guid>
		<description><![CDATA[You think you know how to define a for loop, do you? Scala has 4 different kinds. 1. Traditional for loop. Loops through the members of an Iteratable. The result of the loop block is Unit. Not surprisingly, this loop prints out the members of the collection, in order that they are returned by the [...]]]></description>
			<content:encoded><![CDATA[<p>You think you know how to define a <em>for loop</em>, do you? Scala has <em><strong>4</strong></em> different kinds.</p>
<hr />1. <strong>Traditional for loop</strong>. Loops through the members of an Iteratable. The result of the loop block is <code>Unit</code>.</p>
<div id="wpshdo_10" class="wp-synhighlighter-outer"><div id="wpshdt_10" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_10"></a><a id="wpshat_10" class="wp-synhighlighter-title" href="#codesyntax_10"  onClick="javascript:wpsh_toggleBlock(10)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_10" onClick="javascript:wpsh_code(10)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_10" onClick="javascript:wpsh_print(10)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_10" class="wp-synhighlighter-inner" style="display: block;"><pre class="pascal" style="font-family:monospace;"><span class="kw1">for</span><span class="br0">&#40;</span>mbr &lt;<span class="sy0">-</span> collection<span class="br0">&#41;</span> <span class="coMULTI">{
  println(mbr)
}</span></pre></div></div>
<p>Not surprisingly, this loop prints out the members of the collection, in order that they are returned by the collection&#8217;s iterator. In fact, this loop construct is translated exactly to</p>
<div id="wpshdo_11" class="wp-synhighlighter-outer"><div id="wpshdt_11" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_11"></a><a id="wpshat_11" class="wp-synhighlighter-title" href="#codesyntax_11"  onClick="javascript:wpsh_toggleBlock(11)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_11" onClick="javascript:wpsh_code(11)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_11" onClick="javascript:wpsh_print(11)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_11" class="wp-synhighlighter-inner" style="display: block;"><pre class="pascal" style="font-family:monospace;">collection.<span class="me1">foreach</span><span class="br0">&#40;</span>mbr <span class="sy0">=</span>&gt; println<span class="br0">&#40;</span>mbr<span class="br0">&#41;</span><span class="br0">&#41;</span></pre></div></div>
<hr />2. <strong>For&#8230;Yield Loop</strong>. Use the yield keyword within the body of a for loop. The loop block has a result which is an iterator of the yielded results. Thus the for loop can act as the RHS of an assignment.</p>
<div id="wpshdo_12" class="wp-synhighlighter-outer"><div id="wpshdt_12" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_12"></a><a id="wpshat_12" class="wp-synhighlighter-title" href="#codesyntax_12"  onClick="javascript:wpsh_toggleBlock(12)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_12" onClick="javascript:wpsh_code(12)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_12" onClick="javascript:wpsh_print(12)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_12" class="wp-synhighlighter-inner" style="display: block;"><pre class="pascal" style="font-family:monospace;">val transformed <span class="sy0">=</span> <span class="kw1">for</span><span class="br0">&#40;</span>mbr &lt;<span class="sy0">-</span> collection<span class="br0">&#41;</span> <span class="coMULTI">{
  yield transform(mbr)
}</span></pre></div></div>
<p>Each time through this example loop, the result of the loop is yielded out. All the yielded results are collected in to a single iterator. This type of for loop is syntactic sugar for the following statement</p>
<div id="wpshdo_13" class="wp-synhighlighter-outer"><div id="wpshdt_13" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_13"></a><a id="wpshat_13" class="wp-synhighlighter-title" href="#codesyntax_13"  onClick="javascript:wpsh_toggleBlock(13)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_13" onClick="javascript:wpsh_code(13)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_13" onClick="javascript:wpsh_print(13)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_13" class="wp-synhighlighter-inner" style="display: block;"><pre class="pascal" style="font-family:monospace;">val transformed <span class="sy0">=</span> collection.<span class="me1">map</span><span class="br0">&#40;</span>mbr <span class="sy0">=</span>&gt; transform<span class="br0">&#40;</span>mbr<span class="br0">&#41;</span><span class="br0">&#41;</span></pre></div></div>
<p>That&#8217;s right, a simple for&#8230;yield loop is just syntactic sugar for <code>Iteratable.map()</code>.</p>
<hr /><strong>Interlude: Watch Out for Infinite Iterables</strong></p>
<p>Infinite (or extremely large) iterables, usually implemented as <code>Stream</code>s or <code>Range</code>s, are a bit tricky. For example, it probably wouldn&#8217;t surprise you to learn that the following traditional for loop will not terminate (at least not in your lifetime):</p>
<div id="wpshdo_14" class="wp-synhighlighter-outer"><div id="wpshdt_14" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_14"></a><a id="wpshat_14" class="wp-synhighlighter-title" href="#codesyntax_14"  onClick="javascript:wpsh_toggleBlock(14)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_14" onClick="javascript:wpsh_code(14)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_14" onClick="javascript:wpsh_print(14)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_14" class="wp-synhighlighter-inner" style="display: block;"><pre class="pascal" style="font-family:monospace;"><span class="kw1">for</span><span class="br0">&#40;</span>i &lt;<span class="sy0">-</span> 0 <span class="kw1">to</span> <span class="nu0">100000000000</span><span class="br0">&#41;</span> println<span class="br0">&#40;</span>i<span class="br0">&#41;</span></pre></div></div>
<p>But executing this next for&#8230;yield loop does <em>not</em> cause an indefinite wait &#8212; it works fine! (Go ahead, try it out!)</p>
<div id="wpshdo_15" class="wp-synhighlighter-outer"><div id="wpshdt_15" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_15"></a><a id="wpshat_15" class="wp-synhighlighter-title" href="#codesyntax_15"  onClick="javascript:wpsh_toggleBlock(15)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_15" onClick="javascript:wpsh_code(15)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_15" onClick="javascript:wpsh_print(15)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_15" class="wp-synhighlighter-inner" style="display: block;"><pre class="pascal" style="font-family:monospace;">val numberStrings <span class="sy0">=</span> <span class="kw1">for</span><span class="br0">&#40;</span>i &lt;<span class="sy0">-</span> 0 <span class="kw1">to</span> <span class="nu0">100000000000</span><span class="br0">&#41;</span> yield <span class="br0">&#40;</span><span class="st0">&quot;&quot;</span> <span class="sy0">+</span> i<span class="br0">&#41;</span></pre></div></div>
<p>How can this be so? You need to know that <code>o to 10000000000</code> results in a <code>Range</code> object, which is a non-strict iterator. That is, it is an iterator that calculates the &#8220;next&#8221; value as you iterate through it, rather than pre-computing all members up front and storing them in memory when the <code>Range</code> is created.</p>
<p>Iteratable functions that yield a scalar result, like <code>foldLeft()</code> or <code>length()</code> or any <a href="http://www.blumenfeld-maso.com/2010/01/scala-word-of-the-day-catamorphism/">catamorphic function</a>, are not safe to use with non-strict iterators, because these methods must iterate over the entire iteratable&#8217;s contents to produce a result. The <code>foreach()</code> method falls in to this unsafe category &#8212; <code>foreach()</code>&#8216;s return type is Unit, which is considered scalar.</p>
<p>Remember the traditional for loop is just syntactic sugar for a <code>foreach()</code> call, and this explains why looping over the range with a traditional loop causes an indefinite wait.</p>
<p>Iteratable functions that yield results of similar size to the input, such as <code>map()</code> and <code>flatMap()</code>, are perfectly safe to use with non-strict iterators. These methods themselves yield non-strict iterators, and don&#8217;t need to iterate over the source iterator&#8217;s contents to yield a result.</p>
<p>The for&#8230;yield loop is just syntactic sugar for a <code>map()</code> call, and this explains why looping over the <code>Range</code> with a for&#8230;yield loop doesn&#8217;t cause an indefinite wait.</p>
<p><strong>End of Interlude</strong></p>
<hr />3. <strong>Guarded For&#8230;Yield Loop</strong>. Throw an <em>if</em> guard in to a for..yield loop, and its translated to a filter-map pipeline (perhaps I should say filter |&gt; map, using <a href="http://www.blumenfeld-maso.com/2009/10/pipe-operator-for-scala/">the pipe operator</a>).</p>
<div id="wpshdo_16" class="wp-synhighlighter-outer"><div id="wpshdt_16" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_16"></a><a id="wpshat_16" class="wp-synhighlighter-title" href="#codesyntax_16"  onClick="javascript:wpsh_toggleBlock(16)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_16" onClick="javascript:wpsh_code(16)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_16" onClick="javascript:wpsh_print(16)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_16" class="wp-synhighlighter-inner" style="display: block;"><pre class="pascal" style="font-family:monospace;"><span class="co1">// Using the guarded for...yield loop syntactic sugar</span>
val oddSquares <span class="sy0">=</span>
  <span class="kw1">for</span><span class="br0">&#40;</span>i &lt;<span class="sy0">-</span> 0 <span class="kw1">to</span> 10000000000 <span class="kw1">if</span> i % <span class="nu0">2</span> <span class="sy0">==</span> <span class="nu0">1</span><span class="br0">&#41;</span> yield <span class="br0">&#40;</span>i<span class="sy0">*</span>i<span class="br0">&#41;</span>
&nbsp;
<span class="co1">// Exactly the same thing as</span>
val oddSquares <span class="sy0">=</span> <span class="br0">&#40;</span>0 <span class="kw1">to</span> <span class="nu0">10000000000</span><span class="br0">&#41;</span>.<span class="me1">filter</span><span class="br0">&#40;</span>i<span class="sy0">=</span>&gt;i % <span class="nu0">2</span> <span class="sy0">==</span> <span class="nu0">1</span><span class="br0">&#41;</span>.<span class="me1">map</span><span class="br0">&#40;</span>i<span class="sy0">=</span>&gt;i<span class="sy0">*</span>i<span class="br0">&#41;</span></pre></div></div>
<p>And as the example implies, this for loop style is non-strict collection safe (because both <code>filter()</code> and <code>map()</code> are non-strict safe).</p>
<hr />4. <strong>Nested For Loop</strong>. Nesting iteration over iterators is syntactic sugar for a nested <code>flatMap()</code> call. Stare at the loop below and the form it gets translated in to by the Scala compiler for a little bit, you don&#8217;t need my explanation:</p>
<div id="wpshdo_17" class="wp-synhighlighter-outer"><div id="wpshdt_17" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_17"></a><a id="wpshat_17" class="wp-synhighlighter-title" href="#codesyntax_17"  onClick="javascript:wpsh_toggleBlock(17)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_17" onClick="javascript:wpsh_code(17)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_17" onClick="javascript:wpsh_print(17)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_17" class="wp-synhighlighter-inner" style="display: block;"><pre class="pascal" style="font-family:monospace;"><span class="co1">// Long-winded nested for loop</span>
val pairsThatSumTo100 <span class="sy0">=</span>
  <span class="kw1">for</span><span class="br0">&#40;</span>i &lt;<span class="sy0">-</span> 0 <span class="kw1">to</span> <span class="nu0">100</span>;
      j &lt;<span class="sy0">-</span> i <span class="kw1">to</span> 100 <span class="kw1">if</span> i <span class="sy0">+</span> j <span class="sy0">==</span> <span class="nu0">100</span><span class="br0">&#41;</span>
    yield Pair<span class="br0">&#40;</span>i<span class="sy0">,</span> j<span class="br0">&#41;</span>
&nbsp;
<span class="co1">// Slightly shorter but harder to read raw form that gets compiled</span>
val pairsThatSumTo100 <span class="sy0">=</span>
  <span class="br0">&#40;</span>0 <span class="kw1">to</span> 100<span class="br0">&#41;</span>.<span class="me1">flatMap</span><span class="br0">&#40;</span>i<span class="sy0">=</span>&gt;<span class="br0">&#40;</span>i <span class="kw1">to</span> <span class="nu0">100</span><span class="br0">&#41;</span>.<span class="me1">filter</span><span class="br0">&#40;</span>j<span class="sy0">=</span>&gt;i<span class="sy0">+</span>j<span class="sy0">==</span><span class="nu0">100</span><span class="br0">&#41;</span>.<span class="me1">map</span><span class="br0">&#40;</span>j<span class="sy0">=</span>&gt;Pair<span class="br0">&#40;</span>i<span class="sy0">,</span>j<span class="br0">&#41;</span><span class="br0">&#41;</span><span class="br0">&#41;</span></pre></div></div>
<p>Note that nested for loops are also non-strict safe, because <code>filter()</code>, <code>map()</code> and <code>flatMap()</code> are all non-strict safe. Only the traditional for loop is not safe for non-strict use.
<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.blumenfeld-maso.com%2F2010%2F01%2Fscala-word-of-the-day-for-loops-all-4-kinds%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.blumenfeld-maso.com%2F2010%2F01%2Fscala-word-of-the-day-for-loops-all-4-kinds%2F&amp;source=bmaso&amp;style=normal&amp;service=bit.ly&amp;hashtags=for+loop,iterable,iterator,non-strict,scala" height="61" width="50" /><br />
			</a>
		</div>
]]></content:encoded>
			<wfw:commentRss>http://www.blumenfeld-maso.com/2010/01/scala-word-of-the-day-for-loops-all-4-kinds/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pipe Operator for Scala</title>
		<link>http://www.blumenfeld-maso.com/2009/10/pipe-operator-for-scala/</link>
		<comments>http://www.blumenfeld-maso.com/2009/10/pipe-operator-for-scala/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 17:33:10 +0000</pubDate>
		<dc:creator>Brian Maso</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.blumenfeld-maso.com/?p=5</guid>
		<description><![CDATA[My first not-completely-trivial task in Scala is to implement the equivalent of the F# pipe operator. Quick Explanation of the Pipe Operator The pipe operator is syntactic sugar that makes certain patterns of code easier to read. When generating a final result by a sequence of value calculations its easier to read the sequence from [...]]]></description>
			<content:encoded><![CDATA[<p>My first not-completely-trivial task in Scala is to implement the equivalent of the <a href="http://lorgonblog.spaces.live.com/Blog/cns!701679AD17B6D310!165.entry" target="_blank">F# pipe operator</a>.</p>
<h2>Quick Explanation of the Pipe Operator</h2>
<p>The pipe operator is syntactic sugar that makes certain patterns of code easier to read. When generating a final result by a sequence of value calculations its easier to read the sequence from left -to-right, but Scala  only supports passing values to functions in <em>function(value)</em> form, which basically forces the eyes to read the sequence in right-to-left order &#8212; rather unnatural.</p>
<p>Here is one way of expressing a sequence of calculations, relying on local vals to hold intermediate sequence values:</p>
<div id="wpshdo_18" class="wp-synhighlighter-outer"><div id="wpshdt_18" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_18"></a><a id="wpshat_18" class="wp-synhighlighter-title" href="#codesyntax_18"  onClick="javascript:wpsh_toggleBlock(18)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_18" onClick="javascript:wpsh_code(18)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_18" onClick="javascript:wpsh_print(18)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_18" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;"><a href="http://scala-lang.org"><span class="kw1">def</span></a> shuffle<span class="br0">&#40;</span>str<span class="sy0">:</span> String<span class="br0">&#41;</span><span class="sy0">:</span> String <span class="sy0">=</span> . . .
<a href="http://scala-lang.org"><span class="kw1">def</span></a> randomize<span class="br0">&#40;</span>str<span class="sy0">:</span> String<span class="br0">&#41;</span><span class="sy0">:</span> String <span class="sy0">=</span> . . .
<a href="http://scala-lang.org"><span class="kw1">def</span></a> camelCase<span class="br0">&#40;</span>str<span class="sy0">:</span> String<span class="br0">&#41;</span><span class="sy0">:</span> String <span class="sy0">=</span> . . .
<a href="http://scala-lang.org"><span class="kw1">def</span></a> futzWith<span class="br0">&#40;</span>str<span class="sy0">:</span> String<span class="br0">&#41;</span><span class="sy0">:</span> String <span class="sy0">=</span> . . .
<a href="http://scala-lang.org"><span class="kw1">def</span></a> applySeveralStringTransforms<span class="br0">&#40;</span>str<span class="sy0">:</span> String<span class="br0">&#41;</span><span class="sy0">:</span> String <span class="sy0">=</span> <span class="br0">&#123;</span>
  <a href="http://scala-lang.org"><span class="kw1">val</span></a> shuffled <span class="sy0">=</span> shuffle<span class="br0">&#40;</span>str<span class="br0">&#41;</span>
  <a href="http://scala-lang.org"><span class="kw1">val</span></a> randomized <span class="sy0">=</span> randomize<span class="br0">&#40;</span>shuffled<span class="br0">&#41;</span>
  <a href="http://scala-lang.org"><span class="kw1">val</span></a> camelCased <span class="sy0">=</span> camelCase<span class="br0">&#40;</span>randomized<span class="br0">&#41;</span>
  futzWith<span class="br0">&#40;</span>camelCased<span class="br0">&#41;</span>
<span class="br0">&#125;</span></pre></div></div>
<p>Which reads easy enough &#8212; the result of the function is the result of shuffling, randomizing, camel-casing and finally futzing with the original String. And here&#8217;s the equivalent calculation as a single expression, without local vals. Note how the sequence of calculations is performed from right to left &#8212; first shuffle, then randomize, etc.</p>
<div id="wpshdo_19" class="wp-synhighlighter-outer"><div id="wpshdt_19" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_19"></a><a id="wpshat_19" class="wp-synhighlighter-title" href="#codesyntax_19"  onClick="javascript:wpsh_toggleBlock(19)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_19" onClick="javascript:wpsh_code(19)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_19" onClick="javascript:wpsh_print(19)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_19" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;"><a href="http://scala-lang.org"><span class="kw1">def</span></a> applySeveralStringTransforms<span class="br0">&#40;</span>str<span class="sy0">:</span> String<span class="br0">&#41;</span><span class="sy0">:</span> String <span class="sy0">=</span> <span class="br0">&#123;</span>
  futzWith<span class="br0">&#40;</span>camelCase<span class="br0">&#40;</span>randomize<span class="br0">&#40;</span>shuffle<span class="br0">&#40;</span>str<span class="br0">&#41;</span><span class="br0">&#41;</span><span class="br0">&#41;</span>
<span class="br0">&#125;</span></pre></div></div>
<p>A pipe operator allows you to pass the result of an expression to the right, preserving left-to-right visual order while still being semantically equivalent to either form above:</p>
<div id="wpshdo_20" class="wp-synhighlighter-outer"><div id="wpshdt_20" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_20"></a><a id="wpshat_20" class="wp-synhighlighter-title" href="#codesyntax_20"  onClick="javascript:wpsh_toggleBlock(20)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_20" onClick="javascript:wpsh_code(20)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_20" onClick="javascript:wpsh_print(20)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_20" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;"><a href="http://scala-lang.org"><span class="kw1">def</span></a> applySeveralStringTransforms<span class="br0">&#40;</span>str<span class="sy0">:</span> String<span class="br0">&#41;</span><span class="sy0">:</span> String <span class="sy0">=</span> <span class="br0">&#123;</span>
  str |<span class="sy0">&gt;</span> shuffle |<span class="sy0">&gt;</span> randomize |<span class="sy0">&gt;</span> camelCase |<span class="sy0">&gt;</span> futzWith
<span class="br0">&#125;</span></pre></div></div>
<h2>Attempt # 1: Right-Associative Operator</h2>
<p>My first attempt has me defining a right-associative operator, using <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=179766" target="_blank">Odersky&#8217;s pimp-my-library</a> technique, to generate a temporary PipeFunc object which has a &#8220;|&gt;:&#8221; operator. That is, I&#8217;m using a couple tricks to get the compiler to automatically rewrite this</p>
<div id="wpshdo_21" class="wp-synhighlighter-outer"><div id="wpshdt_21" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_21"></a><a id="wpshat_21" class="wp-synhighlighter-title" href="#codesyntax_21"  onClick="javascript:wpsh_toggleBlock(21)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_21" onClick="javascript:wpsh_code(21)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_21" onClick="javascript:wpsh_print(21)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_21" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;">x |<span class="sy0">&gt;:</span> func</pre></div></div>
<p>like this</p>
<div id="wpshdo_22" class="wp-synhighlighter-outer"><div id="wpshdt_22" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_22"></a><a id="wpshat_22" class="wp-synhighlighter-title" href="#codesyntax_22"  onClick="javascript:wpsh_toggleBlock(22)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_22" onClick="javascript:wpsh_code(22)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_22" onClick="javascript:wpsh_print(22)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_22" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;"><span class="br0">&#40;</span><a href="http://scala-lang.org"><span class="kw1">new</span></a> PipeFunc<span class="br0">&#40;</span>func<span class="br0">&#41;</span><span class="br0">&#41;</span>.|<span class="sy0">&gt;:</span><span class="br0">&#40;</span>x<span class="br0">&#41;</span></pre></div></div>
<p>Since my operator &#8220;|&gt;:&#8221; ends with a colon, Scala treats it as a &#8220;right-associative&#8221; function &#8212; a function of the right-operand &#8220;func&#8221;, rather than a function of the left-operand &#8220;x&#8221;. A very short-lived PipeFunc object gets created by an implicit conversion, and this object has a method named &#8220;|&gt;:&#8221; that gets applied.</p>
<p>Here&#8217;s the definition of my operator:</p>
<div id="wpshdo_23" class="wp-synhighlighter-outer"><div id="wpshdt_23" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_23"></a><a id="wpshat_23" class="wp-synhighlighter-title" href="#codesyntax_23"  onClick="javascript:wpsh_toggleBlock(23)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_23" onClick="javascript:wpsh_code(23)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_23" onClick="javascript:wpsh_print(23)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_23" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;"><a href="http://scala-lang.org"><span class="kw1">object</span></a> Pipeline <span class="br0">&#123;</span>
  <a href="http://scala-lang.org"><span class="kw1">implicit</span></a> <a href="http://scala-lang.org"><span class="kw1">def</span></a> toPipeFunc<span class="br0">&#91;</span>X, Y<span class="br0">&#93;</span><span class="br0">&#40;</span>func<span class="sy0">:</span> X <span class="sy0">=&gt;</span> Y<span class="br0">&#41;</span> <span class="sy0">=</span> <a href="http://scala-lang.org"><span class="kw1">new</span></a> PipeFunc<span class="br0">&#40;</span>func<span class="br0">&#41;</span>
  <a href="http://scala-lang.org"><span class="kw1">class</span></a> PipeFunc<span class="br0">&#91;</span>X, Y<span class="br0">&#93;</span><span class="br0">&#40;</span>func<span class="sy0">:</span> X <span class="sy0">=&gt;</span> Y<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <a href="http://scala-lang.org"><span class="kw1">def</span></a> |<span class="sy0">&gt;:</span><span class="br0">&#40;</span>value<span class="sy0">:</span> X<span class="br0">&#41;</span><span class="sy0">:</span> Y <span class="sy0">=</span> func<span class="br0">&#40;</span>value<span class="br0">&#41;</span>
  <span class="br0">&#125;</span>
<span class="br0">&#125;</span></pre></div></div>
<p>There are immediate problems with this approach. Because of how Scala 2.7.5 (the version I am using) parses this code, it is apparently unable to recognize that the right-hand side of |&gt;: is a function reference. So the following actually causes a compiler error:</p>
<div id="wpshdo_24" class="wp-synhighlighter-outer"><div id="wpshdt_24" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_24"></a><a id="wpshat_24" class="wp-synhighlighter-title" href="#codesyntax_24"  onClick="javascript:wpsh_toggleBlock(24)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_24" onClick="javascript:wpsh_code(24)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_24" onClick="javascript:wpsh_print(24)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_24" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;"><span class="co1">// complains &quot;|&gt;:&quot; is not a function of type Unit</span>
<span class="st0">&quot;Hello, World!&quot;</span> |<span class="sy0">&gt;:</span> println</pre></div></div>
<p>I&#8217;m not sure why this is, but using parens fixes the problem, but makes the expression too surprising and ugly for my taste. I&#8217;m going to have to go back to the drawing board&#8230;</p>
<h2>Attempt #2: Left-Associative Operator</h2>
<p>Instead of augmenting the function argument on the right, I&#8217;ll try augmenting the value argument on the left with a &#8220;|&gt;&#8221; operator. I&#8217;ll use the same pimp-my-library technique to use an implicit conversion of the left-hand object to a temporary object that has a &#8220;|&gt;&#8221; operator, which takes a function as its right-hand argument. That is, I&#8217;m using a couple tricks to get the compiler to automatically convert this</p>
<div id="wpshdo_25" class="wp-synhighlighter-outer"><div id="wpshdt_25" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_25"></a><a id="wpshat_25" class="wp-synhighlighter-title" href="#codesyntax_25"  onClick="javascript:wpsh_toggleBlock(25)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_25" onClick="javascript:wpsh_code(25)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_25" onClick="javascript:wpsh_print(25)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_25" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;">x |<span class="sy0">&gt;</span> func</pre></div></div>
<p>to this</p>
<div id="wpshdo_26" class="wp-synhighlighter-outer"><div id="wpshdt_26" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_26"></a><a id="wpshat_26" class="wp-synhighlighter-title" href="#codesyntax_26"  onClick="javascript:wpsh_toggleBlock(26)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_26" onClick="javascript:wpsh_code(26)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_26" onClick="javascript:wpsh_print(26)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_26" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;"><span class="br0">&#40;</span><a href="http://scala-lang.org"><span class="kw1">new</span></a> PipeLink<span class="br0">&#40;</span>x<span class="br0">&#41;</span><span class="br0">&#41;</span>.|<span class="sy0">&gt;</span><span class="br0">&#40;</span>func<span class="br0">&#41;</span></pre></div></div>
<p>Here&#8217;s my code for the operator definition:</p>
<div id="wpshdo_27" class="wp-synhighlighter-outer"><div id="wpshdt_27" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_27"></a><a id="wpshat_27" class="wp-synhighlighter-title" href="#codesyntax_27"  onClick="javascript:wpsh_toggleBlock(27)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_27" onClick="javascript:wpsh_code(27)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_27" onClick="javascript:wpsh_print(27)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_27" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;"><a href="http://scala-lang.org"><span class="kw1">object</span></a> Pipeline <span class="br0">&#123;</span>
  <a href="http://scala-lang.org"><span class="kw1">implicit</span></a> <a href="http://scala-lang.org"><span class="kw1">def</span></a> toPipeLink<span class="br0">&#91;</span>X<span class="br0">&#93;</span><span class="br0">&#40;</span>v<span class="sy0">:</span> X<span class="br0">&#41;</span><span class="sy0">:</span> PipeLink<span class="br0">&#91;</span>X<span class="br0">&#93;</span> <span class="sy0">=</span> <a href="http://scala-lang.org"><span class="kw1">new</span></a> PipeLink<span class="br0">&#91;</span>X<span class="br0">&#93;</span><span class="br0">&#40;</span>v<span class="br0">&#41;</span>
  <a href="http://scala-lang.org"><span class="kw1">class</span></a> PipeLink<span class="br0">&#91;</span>X<span class="br0">&#93;</span><span class="br0">&#40;</span>value<span class="sy0">:</span> X<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <a href="http://scala-lang.org"><span class="kw1">def</span></a> |<span class="sy0">&gt;</span><span class="br0">&#91;</span>Y<span class="br0">&#93;</span><span class="br0">&#40;</span>func<span class="sy0">:</span> X <span class="sy0">=&gt;</span> Y<span class="br0">&#41;</span><span class="sy0">:</span> Y <span class="sy0">=</span> func<span class="br0">&#40;</span>value<span class="br0">&#41;</span>
  <span class="br0">&#125;</span>
<span class="br0">&#125;</span></pre></div></div>
<p>OK, works correctly, and doesn&#8217;t have any of the problems that the right-associative operator had.</p>
<p>I do have a hidden performance issue: creation of an very-short-lived temporary object. Consider how the the following single expression gets rewritten by the Scala compiler:</p>
<div id="wpshdo_28" class="wp-synhighlighter-outer"><div id="wpshdt_28" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_28"></a><a id="wpshat_28" class="wp-synhighlighter-title" href="#codesyntax_28"  onClick="javascript:wpsh_toggleBlock(28)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_28" onClick="javascript:wpsh_code(28)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_28" onClick="javascript:wpsh_print(28)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_28" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;">str |<span class="sy0">&gt;</span> shuffle |<span class="sy0">&gt;</span> randomize |<span class="sy0">&gt;</span> camelCase |<span class="sy0">&gt;</span> futzWith</pre></div></div>
<p>to this:</p>
<div id="wpshdo_29" class="wp-synhighlighter-outer"><div id="wpshdt_29" class="wp-synhighlighter-expanded"><table border="0" width="100%"><tr><td align="left" width="80%"><a name="#codesyntax_29"></a><a id="wpshat_29" class="wp-synhighlighter-title" href="#codesyntax_29"  onClick="javascript:wpsh_toggleBlock(29)" title="Click to show/hide code block">Code block</a></td><td align="right"><a href="#codesyntax_29" onClick="javascript:wpsh_code(29)" title="Show code only"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/code.png" /></a>&nbsp;<a href="#codesyntax_29" onClick="javascript:wpsh_print(29)" title="Print code"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/printer.png" /></a>&nbsp;<a href="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/About.html" target="_blank" title="Show plugin information"><img border="0" style="border: 0 none" src="http://www.blumenfeld-maso.com/wp-content/plugins/wp-synhighlight/themes/default/images/info.gif" /></a>&nbsp;</td></tr></table></div><div id="wpshdi_29" class="wp-synhighlighter-inner" style="display: block;"><pre class="scala" style="font-family:monospace;"><span class="br0">&#40;</span><a href="http://scala-lang.org"><span class="kw1">new</span></a> PipeLink<span class="br0">&#40;</span><span class="br0">&#40;</span><a href="http://scala-lang.org"><span class="kw1">new</span></a> PipeLink<span class="br0">&#40;</span><span class="br0">&#40;</span><a href="http://scala-lang.org"><span class="kw1">new</span></a> PipeLink<span class="br0">&#40;</span><span class="br0">&#40;</span><a href="http://scala-lang.org"><span class="kw1">new</span></a> PipeLink<span class="br0">&#40;</span>str<span class="br0">&#41;</span><span class="br0">&#41;</span>.
    |<span class="sy0">&gt;</span><span class="br0">&#40;</span>shuffle<span class="br0">&#41;</span><span class="br0">&#41;</span>.|<span class="sy0">&gt;</span><span class="br0">&#40;</span>randomize<span class="br0">&#41;</span><span class="br0">&#41;</span>.|<span class="sy0">&gt;</span><span class="br0">&#40;</span>camelCase<span class="br0">&#41;</span><span class="br0">&#41;</span>.|<span class="sy0">&gt;</span><span class="br0">&#40;</span>futzWith<span class="br0">&#41;</span></pre></div></div>
<p>Ugly &#8211; obviously; wastefully creates too many objects &#8211; also true. 4 temporary PipeLinks created and thrown away. The JVM GC is pretty good at handling short-lived objects, but this is terribly wasteful. I can&#8217;t think of a way of getting rid of temporary objects &#8212; any suggestions greatly appreciated!</p>
<h2>Smarter Than Me</h2>
<p>Only after implementing did I find that <a href="http://www.blogger.com/profile/03622573187942388226" target="_blank">Steve Gilham</a> had already posted his <a href="http://stevegilham.blogspot.com/2009/01/pipe-operator-in-scala.html" target="_blank">implementation of the pipe operator</a>. He immediately went with a left-associative operator implementation. Must be a clever guy! Both his solution and mine suffer from creating a temp object with each invocation of the pipe operator.</p>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 1618px; width: 1px; height: 1px;">// complains &#8220;|&gt;:&#8221; is not a function of type Unit</div>
<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.blumenfeld-maso.com%2F2009%2F10%2Fpipe-operator-for-scala%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.blumenfeld-maso.com%2F2009%2F10%2Fpipe-operator-for-scala%2F&amp;source=bmaso&amp;style=normal&amp;service=bit.ly&amp;hashtags=scala" height="61" width="50" /><br />
			</a>
		</div>
]]></content:encoded>
			<wfw:commentRss>http://www.blumenfeld-maso.com/2009/10/pipe-operator-for-scala/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

