<?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>Derek Wyatt&#039;s Blog</title>
	<atom:link href="http://www.derekwyatt.org/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.derekwyatt.org</link>
	<description>Vim... and stuff</description>
	<lastBuildDate>Thu, 26 Jan 2012 01:31:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Haskell &#8216;sequence&#8217; Over Functions &#8211; Explained</title>
		<link>http://www.derekwyatt.org/2012/01/25/haskell-sequence-over-functions-explained/</link>
		<comments>http://www.derekwyatt.org/2012/01/25/haskell-sequence-over-functions-explained/#comments</comments>
		<pubDate>Thu, 26 Jan 2012 00:18:41 +0000</pubDate>
		<dc:creator>Derek Wyatt</dc:creator>
				<category><![CDATA[Functional]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[functional]]></category>
		<category><![CDATA[haskell]]></category>

		<guid isPermaLink="false">http://www.derekwyatt.org/?p=413</guid>
		<description><![CDATA[I&#8217;ve recently been devouring Learn You a Haskell for Great Good. I&#8217;ve been meaning to do it for ages, but a recent post by Debasish Ghosh pushed me to go through it cover to cover&#8230; I&#8217;m almost there :) I was wrestling over the complexities of applying the sequence function to a list of functions. [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve recently been devouring <a href="http://learnyouahaskell.com">Learn You a Haskell for Great Good</a>. I&#8217;ve been meaning to do it for ages, but a <a href="http://debasishg.blogspot.com/2012/01/2011-year-that-was.html">recent post</a> by <a href="http://debasishg.blogspot.com">Debasish Ghosh</a> pushed me to go through it cover to cover&#8230; I&#8217;m almost there :)</p>
<p>I was wrestling over the complexities of applying the <code>sequence</code> function to a list of functions. More succinctly, I was confused on the mechanics of how this worked:</p>
<pre class="haskell">ghci&gt; sequence [(&gt; 4), (&lt; 10), odd] 7
[True, True, True]</pre>
<p>To figure it out, all you have to do is reduce it, and then reduce it, and then reduce it some more. Let&#8217;s do that.</p>
<p>First, <code>sequence</code> is defined as (I&#8217;m using the definition of <code>sequenceA</code> from LYAH, as opposed to the definition of <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:sequence">sequence from the Haskell API</a>):</p>
<pre class="haskell">sequence :: (Applicative f) =&gt; [f a] -&gt; f [a]
sequence = foldr (liftA2 (:)) (pure [])</pre>
<p>And the definition of the <a href="http://en.wikibooks.org/wiki/Haskell/Applicative_Functors">Applicative Functor</a> instance for functions is:</p>
<pre class="haskell">instance :: Functor ((-&gt;) r) where
    pure x = (\_ -&gt; x)
    f &lt;*&gt; g = (\x -&gt; f x (g x))</pre>
<p>Now, let&#8217;s expand (note, I&#8217;m not going into nauseating detail here, and assume you&#8217;ve gone part of the way thus far):</p>
<pre class="haskell">
sequence [(&gt; 4), (&lt; 10), odd]
-- becomes
foldr (liftA2 (:)) (pure []) [(&gt; 4), (&lt; 10), odd]
-- which becomes, due to the definition of liftA2
((:) . (&gt; 4)) &lt;*&gt; (((:) . (&lt; 10)) &lt;*&gt; (((:) . odd) &lt;*&gt; (pure [])))
</pre>
<p>Ok, so we&#8217;ve expanded the <code>foldr</code> and now we can expand the <code>&lt;*&gt;</code> and the <code>pure []</code>:</p>
<pre class="haskell">
(\x -&gt; ((:) . (&gt; 4)) x (
    \x -&gt; ((:) . (&lt; 10)) x (
        \x -&gt; ((:) . odd) x ((\_ -&gt; []) x)) x) x)</pre>
<p>Ok, that&#8217;s a bit rough to read&#8230; the key to it is noting how the <code>'x'</code> gets propagated. Let&#8217;s take another look:</p>
<p><img src="/wp-content/uploads/2012/01/Applicative_Function.png" alt="" /></p>
<p>When we pass in the <code>7</code> it gets propagated to all of the little <code>x</code>&#8216;s, and all of those little <code>x</code>&#8216;s get passed to their composed functions, and each of those results in a new element on the list:</p>
<pre class="&quot;haskell">
(\x -&gt; ((:) . odd) x ((\_ -&gt; []) x)) 7
-- reduces to
((:) . odd) 7 (\_ -&gt; []) 7)
-- which reduces to
(: True [])
-- which becomes
[True]

-- Now, we use that to reduce the next level up
((:) . (&lt; 10) 7) [True]
-- which becomes
(: True [True])
-- which becomes
[True, True]

-- And now our last level
((:) . (&gt; 4) 7) [True, True]
-- which becomes
(: True [True, True])
-- which becomes
[True, True, True]
</pre>
<p>Ah, that&#8217;s better&#8230; now that I &#8216;get it&#8217;, I can move on.</p>
<p>Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.derekwyatt.org/2012/01/25/haskell-sequence-over-functions-explained/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Monad posting updated</title>
		<link>http://www.derekwyatt.org/2011/09/02/monad-posting-updated/</link>
		<comments>http://www.derekwyatt.org/2011/09/02/monad-posting-updated/#comments</comments>
		<pubDate>Fri, 02 Sep 2011 14:14:48 +0000</pubDate>
		<dc:creator>Derek Wyatt</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.derekwyatt.org/2011/09/02/monad-posting-updated/</guid>
		<description><![CDATA[A couple of people pointed out that my posting about why Monads are so awesome left a bit too much to the imagination. I tossed in an update that should make it less mysterious about what the heck I&#8217;m talking about.]]></description>
			<content:encoded><![CDATA[<p>A couple of people pointed out that <a href="/2011/09/01/heres-one-of-the-reasons-why-monads-are-awesome/">my posting about why Monads are so awesome</a> left a bit too much to the imagination.  I tossed in an <a href="/2011/09/01/heres-one-of-the-reasons-why-monads-are-awesome#update">update</a> that should make it less mysterious about what the heck I&#8217;m talking about.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.derekwyatt.org/2011/09/02/monad-posting-updated/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Here&#8217;s (one of the reasons) why Scala is awesome</title>
		<link>http://www.derekwyatt.org/2011/09/01/heres-one-of-the-reasons-why-monads-are-awesome/</link>
		<comments>http://www.derekwyatt.org/2011/09/01/heres-one-of-the-reasons-why-monads-are-awesome/#comments</comments>
		<pubDate>Thu, 01 Sep 2011 16:57:39 +0000</pubDate>
		<dc:creator>Derek Wyatt</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.derekwyatt.org/?p=391</guid>
		<description><![CDATA[Update: In the comments below, Alex is trying to educate me on something&#8230; I&#8217;m still not entirely sure what he&#8217;s on about but it&#8217;s been keeping me thinking about this post. I&#8217;ve modified it a bit here and there to try and be more correct. Essentially, I think I&#8217;ve been attributing too much to Monads [...]]]></description>
			<content:encoded><![CDATA[<p><b>Update:</b> In the comments below, Alex is trying to educate me on something&#8230; I&#8217;m still not entirely sure what he&#8217;s on about but it&#8217;s been keeping me thinking about this post.  I&#8217;ve modified it a bit here and there to try and be more correct.  Essentially, I think I&#8217;ve been attributing too much to Monads where only part of what I like is attributed to them where the other part is attributed to partial functions (or function composition).</p>
<p>Ok, I&#8217;m no <a href="http://www.codecommit.com/blog/ruby/monads-are-not-metaphors" title="Daniel Spiewak sent me to this page... I read pretty much anything he says">Monad</a> expert by any stretch of the imagination&#8230; seriously.  But, I did something today that has me so jazzed about Monads, partial functions and <a href="http://www.scala-lang.org">Scala</a> in general, that I just gotta share.</p>
<p>So my task was to take some <a href="http://www.json.org" title="How can it be that THE JSON page is so utterly hideous?  I mean, really, it's worse than my website">JSON</a> and convert it to a structure of my own classes, but still really general &#8211; i.e. we&#8217;re not talking about &#8220;real&#8221; marshalling here.</p>
<p>So I took a simple approach, and used the Scala Library&#8217;s <a href="http://www.scala-lang.org/api/current/index.html#scala.util.parsing.json.JSON$" title="I'll use something 'better' if the need ever arises.">JSON Module</a>.  I had to deal with type-casting, defaulting of values, and constraint checking (i.e. <i>field X must be defined</i>).  The code to do all of this is so simple and so awesome that it&#8217;s just hard to believe.  Now, it&#8217;s not perfect&#8230; I&#8217;ll shore it up over the next while as need requires&#8230; but it&#8217;s passing all of my tests pretty nicely right now.</p>
<p>I want to convert the following JSON:</p>
<pre class="brush:javascript">
{
  "vendor"  : "Whoever", // required
  "colour"  : "blue",    // default to "None"
  "widgets" :            // default to Empty list of strings
  [
    {
      "name"    : "One",   // required
      "flavour" : "Lime"   // default to Strawberry
    },
    {
      "name"    : "Two",   // required
      "flavour" : "Banana" // default to Strawberry
    }
  ]
}
</pre>
<p>to the following concrete Scala:</p>
<pre class="brush:scala">
case class Widget(name: String, flavour: String)
case class Contract(vendor: String, colour: String, widgets: List[Widget])
Contract("Whoever", "blue", List(Widget("One", "Lime"),
                                 Widget("Two", "Banana")))
</pre>
<p>I used a <a href="http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-4" title="Daniel Spiewak again... love that dood.">Pattern Matching</a> example for this sort of thing from <a href="http://stackoverflow.com/questions/4170949/how-to-parse-json-in-scala-using-standard-scala-classes">an awesome StackOverflow post</a> as a starter and then fleshed it out to meet my requirements.  Here it is:</p>
<pre class="brush:scala">
// Types we need
case class Widget(name: String, flavour: String)
case class Contract(vendor: String, colour: String, widgets: List[Widget])

object Contract {
  // The class caster that came from the StackOverflow page
  // Yeah, this can throw exceptions... I don't care about
  // those for this example
  class ClassCaster[T] {
    def unapply(a: Any): Option[T] = Some(a.asInstanceOf[T])
  }

  // Concrete instances of the casters for pattern matching
  object AsMap extends ClassCaster[Map[String, Any]]
  object AsList extends ClassCaster[List[Any]]
  object AsString extends ClassCaster[String]

  // It can happen
  case class ContractException(message: String) extends Exception(message)

  // Returns an Either that is a hell of a lot more deterministic than
  // throwing exceptions around
  def fromJSON(json: String): Either[ContractException, Contract] = {
    // Helps us get rid of boilerplate
    def error[T](prefix: String): Option[T] =
      throw ContractException("%s must be specified".format(prefix))

    // Catch the exceptions and turn them into Left() instances
    try {
      val parsed = JSON.parseFull(json)
      if (parsed.isEmpty) throw ContractException("Unable to parse JSON.")

      // Here comes the monad / partial function love...
      val contract = for {
        Some(AsMap(map))  < - List(parsed)
        AsString(vendor)  <- map get "vendor" orElse error("vendor")
        AsString(colour)  <- map get "colour" orElse Some("None")
        AsList(widgets)   <- map get "widgets"
      } yield Contract(vendor, colour, for {
          AsMap(widget)     <- widgets
          AsString(name)    <- widget get "name" orElse error("name")
          AsString(flavour) <- widget get "flavour" orElse Some("Strawberry")
        } yield Widget(name, flavour)
      )
      Right(contract.head)
    } catch {
      case e: ContractException =>
        Left(e)
      case e =>
        Left(ContractException(e.getMessage))
    }
  }
}
</pre>
<p>It&#8217;s very impressive what this code actually handles when you start digging into it.  I&#8217;m sure you can easily think about what it would be like to code this in Java (or spaghetti monster forbid C++) and know that it&#8217;s going to be a <i>lot</i> more verbose and probably a lot less reliable.</p>
<p id="update"><b>UPDATE:</b> One of the key reasons why the above is so cool is this:</p>
<pre class="brush:scala">
&lt;- map get "colour" orElse Some("None")
&lt;- widget get "name" orElse error("name")
</pre>
<p>By using a generator syntax (&lt;-) and the <code>get</code> function on <a href="http://www.scala-lang.org/api/current/index.html#scala.collection.Map">Map</a> we get to work at a higher abstraction that allows us to chain the decision making process rather than what the imperative approach would demand of us.  It&#8217;s the monadic and compositional nature of <code>Option</code> that allows us to do this.  Consider:</p>
<pre class="brush:java">
String colour = map.get("colour");
if (colour == null)
  colour = "None";

String name = widget.get("name");
if (name == null)
  error("name");
</pre>
<p>I&#8217;m going to editorialise (I mean, this is my blog after all) and point out the following problems:</p>
<ul>
<li>It&#8217;s unclear.  Sure, if you&#8217;ve seen it a million times (and let&#8217;s face, you have&#8230; we all have) you know exactly what this &#8220;means&#8221; but that&#8217;s not because its meaning is clear.</li>
<li>It&#8217;s not syntactically atomic.  Some nasty merge, or some careless programmer can easily insert something between lines 1 and 2 that uses <code>colour</code>.</li>
<li>It&#8217;s repetitive in a bad way (is there a good way?).  That pattern is going to be copy-pasted over and over again.  How many times do you see &#8220;colour&#8221; in there?  Yeah&#8230; three.  So if I copy-paste that and forget to change the third one, you get this:</li>
</ul>
<pre class="brush:java">
String flavour = widget.get("flavour");
if (flavour == null)
  colour = "None";
</pre>
<p>GHACK!</p>
<p>We need to program at a higher level.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.derekwyatt.org/2011/09/01/heres-one-of-the-reasons-why-monads-are-awesome/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>My BASH directory management</title>
		<link>http://www.derekwyatt.org/2011/08/18/my-bash-directory-management/</link>
		<comments>http://www.derekwyatt.org/2011/08/18/my-bash-directory-management/#comments</comments>
		<pubDate>Thu, 18 Aug 2011 10:10:30 +0000</pubDate>
		<dc:creator>Derek Wyatt</dc:creator>
				<category><![CDATA[Unix]]></category>
		<category><![CDATA[bash]]></category>

		<guid isPermaLink="false">http://www.derekwyatt.org/2011/08/18/my-bash-directory-management/</guid>
		<description><![CDATA[I saw a post on Supuser.com that asked about how to go &#8220;back&#8221; to a directory rather than &#8220;up&#8221;. The right answer was &#8220;cd -&#8220;, of course, but I&#8217;ve been using a home-grown tool to do this for years and it works really well. It started out as a Korn Shell so there are some [...]]]></description>
			<content:encoded><![CDATA[<p>I saw a post on <a href="http://superuser.com/questions/324512/cd-option-to-go-back-rather-than-up">Supuser.com</a> that asked about how to go &#8220;back&#8221; to a directory rather than &#8220;up&#8221;.  The right answer was &#8220;<code>cd -</code>&#8220;, of course, but I&#8217;ve been using a home-grown tool to do this for years and it works really well.</p>
<p>It started out as a <a href="http://www.kornshell.com/" title="Watch your eyes when you click that link... whoah, what an ugly website.">Korn Shell</a> so there are some remnants of that in it, but it does work for <a href="http://www.gnu.org/s/bash/">Bash</a>.</p>
<p>It does the usual thing of replacing the &#8216;<code>cd</code>&#8216; built-in command with a function by aliasing it away.  Every time you change directories, it saves the last place on the stack (up to a max of 15).  You can look at the directory history and switch to any of them based on their number and also a regular expression.</p>
<p>This sort of functionality, whether you use mine or someone else&#8217;s or build your own, is <b>vital</b> to efficient command line <i>kung-fu</i>.  How the hell have you been surviving this long without it???</p>
<p>Here&#8217;s the <a href="https://gist.github.com/1154129">Gist</a> of the code that you can grab.</p>
<ul>
<li><b><code>cd</code></b> &#8211; You know what this does.  And, yes, both <code>cd -</code> and <code>cd {pat} {subst}</code> should also work just fine.</li>
<li><b><code>ss</code></b> &#8211; Short for &#8220;show stack&#8221;.</li>
<li><b><code>csd</code></b> &#8211; Short for &#8220;change to stacked directory&#8221;.  This is the fun one that I&#8217;ll show in an example below.</li>
</ul>
<p>Here&#8217;s how you use it (I&#8217;ll leave it to you to read what I&#8217;m doing and figure out how you can use it):</p>
<pre>
--(/home/dwyatt/scala/scala/src/library/scala/collection/generic)--------------------------------------
--> ss
1) /home/dwyatt/scala/scala/src/library/scala
2) /home/dwyatt/scala/scala/src/library/scala/concurrent
3) /home/dwyatt/scala/scala/src/library/scala/collection/mutable
4) /home/dwyatt/scala/scala/src/library/scala/collection/immutable
5) /home/dwyatt/scala/scala
6) /home/dwyatt/scala
7) /home/dwyatt
--(/home/dwyatt/scala/scala/src/library/scala/collection/generic)--------------------------------------
--> csd 4
--(/home/dwyatt/scala/scala/src/library/scala/collection/immutable)------------------------------------
--> ss
1) /home/dwyatt/scala/scala/src/library/scala/collection/generic
2) /home/dwyatt/scala/scala/src/library/scala
3) /home/dwyatt/scala/scala/src/library/scala/concurrent
4) /home/dwyatt/scala/scala/src/library/scala/collection/mutable
5) /home/dwyatt/scala/scala
6) /home/dwyatt/scala
7) /home/dwyatt
--(/home/dwyatt/scala/scala/src/library/scala/collection/immutable)------------------------------------
--> csd ent$
--(/home/dwyatt/scala/scala/src/library/scala/concurrent)----------------------------------------------
--> ss
1) /home/dwyatt/scala/scala/src/library/scala/collection/immutable
2) /home/dwyatt/scala/scala/src/library/scala/collection/generic
3) /home/dwyatt/scala/scala/src/library/scala
4) /home/dwyatt/scala/scala/src/library/scala/collection/mutable
5) /home/dwyatt/scala/scala
6) /home/dwyatt/scala
7) /home/dwyatt
--(/home/dwyatt/scala/scala/src/library/scala/concurrent)----------------------------------------------
--> csd 5
--(/home/dwyatt/scala/scala)---------------------------------------------------------------------------
--> ss
1) /home/dwyatt/scala/scala/src/library/scala/concurrent
2) /home/dwyatt/scala/scala/src/library/scala/collection/immutable
3) /home/dwyatt/scala/scala/src/library/scala/collection/generic
4) /home/dwyatt/scala/scala/src/library/scala
5) /home/dwyatt/scala/scala/src/library/scala/collection/mutable
6) /home/dwyatt/scala
7) /home/dwyatt
--(/home/dwyatt/scala/scala)---------------------------------------------------------------------------
--> cd ~
--(/home/dwyatt)--------------------------------------------------------------------------------------------
--> cd -
--(/home/dwyatt/scala/scala)---------------------------------------------------------------------------
-->
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.derekwyatt.org/2011/08/18/my-bash-directory-management/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Understanding Scala Streams through Fibonacci</title>
		<link>http://www.derekwyatt.org/2011/07/29/understanding-scala-streams-through-fibonacci/</link>
		<comments>http://www.derekwyatt.org/2011/07/29/understanding-scala-streams-through-fibonacci/#comments</comments>
		<pubDate>Fri, 29 Jul 2011 11:22:25 +0000</pubDate>
		<dc:creator>Derek Wyatt</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.derekwyatt.org/?p=338</guid>
		<description><![CDATA[I took a look at Scala Streams tonight (or was that last night? When am I posting this?) and thought I&#8217;d share what I learned from Literate Programs and the Scala source code. Streams For the uninitiated, a Stream in Scala helps realize one of the fundamental concepts of Functional Programming, that of laziness. In [...]]]></description>
			<content:encoded><![CDATA[<p>I took a look at <a href="http://scala-lang.org">Scala</a> <a href="http://blog.danielwellman.com/2008/03/streams-in-scal.html">Streams</a> tonight (or was that last night? When am I posting this?) and thought I&#8217;d share what I learned from <a href="http://en.literateprograms.org/Fibonacci_numbers_%28Scala%29">Literate Programs</a> and the Scala source code.</p>
<h2>Streams</h2>
<p>For the uninitiated, a <em>Stream</em> in Scala helps realize one of the fundamental concepts of <a href="http://www.joelonsoftware.com/items/2006/08/01.html">Functional Programming</a>, that of <a href="http://en.wikipedia.org/wiki/Lazy_evaluation"><em>laziness</em></a>. In essence, a <em>Stream</em> as infinite &#8211; think of a <a title="The Scala Collection library is one of those things about Scala that, 'if you look at Scala for only one reason, this would be it', except that there are about a dozen of those 'things'" href="http://www.codecommit.com/blog/scala/scala-collections-for-the-easily-bored-part-1">collection</a> that just goes on and on and on and on and on and on. It would be <a title="Seriously... this chick is too dumb to really warrant our time - Yes, I understand the irony of linking to her here... shut up and keep reading" href="http://en.wikipedia.org/wiki/Paris_Hilton">asinine</a> to construct the entire collection before ever using it as that would only ensure that you never used it. A <em>Stream</em> is evaluated on an as-needed basis and only up to the point that you need it.</p>
<h2>The Delicious, Delicious Code&#8230;</h2>
<p>Let&#8217;s illustrate using good ol&#8217; <a title="Fibonacci numbers are the 'other' facility used to illustrate programming concepts - there are only two, and the other is 'Hello World'." href="http://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci Numbers</a>. We&#8217;ll construct a <em>Stream</em> recursively because that&#8217;s more fun and it gives more meat to discuss. (This example comes straight from <a href="http://en.literateprograms.org/Fibonacci_numbers_%28Scala%29">the Literate Programs</a> website but I&#8217;m hoping to explain it in a bit more depth, and not get it too wrong in the process)</p>
<pre class="brush:scala">import scala.math.BigInt
lazy val fibs: Stream[BigInt] = BigInt(0) #::
                                BigInt(1) #::
                                fibs.zip(fibs.tail).map { n =&gt; n._1 + n._2 }</pre>
<p>(<strong>Note:</strong> The above must all be on one line or the compiler is going to have a tough time pimping it out)</p>
<p>Sweet and delicious, no?</p>
<h2>Dissection</h2>
<p>Let&#8217;s break it down:</p>
<p><strong>lazy</strong></p>
<dl>
<dt></dt>
<dd>Strictly speaking, this isn&#8217;t needed, but why not be as lazy as you can possibly be? For the truly uninitiated, this ensures that the <code>fibs</code> value is not evaluated until it&#8217;s actually used.</dd>
<dt></dt>
</dl>
<p><strong>val fibs: Stream[BigInt]</strong></p>
<dl>
<dt></dt>
<dd>&#8220;What the hell is this? I thought Scala <em>inferred</em> types!&#8221;, I hear you scream. Scala does infer types but we&#8217;re defining a <em>recursive value</em> here and Scala needs to understand that the recursive call is a recursive call on a <em>Stream</em> as opposed to a <em>String</em> or some other completely unrelated type.</dd>
<dt></dt>
</dl>
<p><strong>BigInt(0) #:: BigInt(1) #::</strong></p>
<dl>
<dt></dt>
<dd>The Fibonacci series starts with 0 and 1 so we shove those in right here. But what&#8217;s this <code>#::</code> stuff? Here&#8217;s our first <em>real</em> magical point and even the somewhat initiated may be scratching their heads at this one.</p>
<p>If you look at the <a title="I'm directing this topic at to Scala 2.9.0 right now as opposed to 'current' because I have no idea what will happen in the future" href="http://www.scala-lang.org/api/2.9.0/index.html#scala.collection.immutable.Stream">Stream</a> api you won&#8217;t find the <code>#::</code> member function anywhere, and indeed you shouldn&#8217;t as we&#8217;re not working with a <em>Stream</em> right now, but a <a title="My Int's bigger than yours" href="http://www.scala-lang.org/api/2.9.0/index.html#scala.math.BigInt">BigInt</a>.</p>
<p>So with that realization in place, we must also recognize that methods ending in <code>:</code> are <a title="Someone wanted to call it 'wrong associative' but Martin fired that guy" href="http://stackoverflow.com/questions/1162924/what-good-are-right-associative-methods-in-scala">right associative</a>. What this means is that the object we&#8217;re calling the <code>#::</code> method on is actually the <em>Stream</em> object that is returned from the <code>map</code> command at the end of the call (we&#8217;ll get back to that, just hang on). Remember how we had to declare that <code>fibs</code> was a <em>Stream</em> instead of letting Scala infer it? Well, that&#8217;s (one of the reasons) why we need to do that.</p>
<p>Now we know that the method is being called on the <em>Stream</em> but when we look at the <a href="http://www.scala-lang.org/api/2.9.0/index.html#scala.collection.immutable.Stream">api</a> for <em>Stream</em>, again we don&#8217;t see that method call. So where is it?</p>
<p>This method gets <a href="http://scala.sygneca.com/patterns/pimp-my-library">pimped on</a> through the <code>implicit def consWrapper[A](stream: =&gt; Stream): ConsWrapper[A]</code> method defined on the <a href="http://www.scala-lang.org/api/2.9.0/index.html#scala.collection.immutable.Stream$">Stream companion object</a>. Scala will resolve the lack of a <code>#::</code> method on <em>Stream</em> by finding an implicit conversion to a type that does have that method, and this is the <a title="I once knew this guy who was a Rapper that spent five years in jail... coincidence?" href="http://www.scala-lang.org/api/2.9.0/index.html#scala.collection.immutable.Stream$$ConsWrapper">ConsWrapper</a>. The result of that method is to return a new <em>Stream</em>.</p>
<p>Ok, but how&#8217;s that of any use? The conversion to <em>ConsWrapper</em> is going to kill us due to the fact that it&#8217;s going to call the recursive function&#8230; or is it? Well, of course it&#8217;s not. If you look at the paramter to the <em>ConsWrapper</em> you&#8217;ll see why this doesn&#8217;t cause immediate recursion: <code>new ConsWrapper(tl: =&gt; Stream[A])</code>. That&#8217;s a <a href="http://locrianmode.blogspot.com/2011/07/scala-by-name-parameter.html">by-name parameter</a>. This means that it&#8217;s not invoked until it&#8217;s used.</p>
<p>Wow, that&#8217;s a lot of stuff for one bullet point.</p>
</dd>
<dt></dt>
</dl>
<p><strong>fibs.zip(fibs.tail)</strong></p>
<dl>
<dt></dt>
<dd>Go look at <a title="I bet you didn't even hover over this link." href="http://www.scala-lang.org/api/2.9.0/index.html#scala.collection.immutable.Stream">the Stream api</a> again, specifically the <code>zip</code>. I&#8217;ll wait.</p>
<p>You didn&#8217;t read it, did you? Fine&#8230; on your own head, be it.</p>
<p>The size of the Stream returned by <code>tail</code> is one-less than the size of the Stream itself. This means that the <em>zipped</em> result is going to be the size of the Stream returned by <em>tail, not the size of the Stream itself</em>. So, in the initial case (where the Stream is <code>Stream(0, 1, [Stream])</code>, the zipped result is actually <code>Stream((0, 1), ([Stream]))</code> because the tail, of one element, is paired with the head.</p>
<p><code>Stream.zip</code> creates a <code>Cons</code> cell containing <code>(this.head, that.head)</code> as the <code>Cons</code> head and <code>(this.tail zip that.tail)</code> as the <code>Cons</code> tail but <em>as a Stream of <code>(A1, B)</code></em> so we&#8217;re not evaluating it now &#8211; we&#8217;ll evaluate it when it gets called.</p>
</dd>
<dt></dt>
</dl>
<p><strong>map { n =&gt; n._1 + n._2 }</strong></p>
<dl>
<dt></dt>
<dd>Hmmm&#8230; I hesitate to say &#8220;duh?&#8221; but it really does seem appropriate to do so. I mean, if you&#8217;ve made it this far, you know what this does.</p>
</dd>
</dl>
<h2>Use it</h2>
<p>Ok, so what happens when we evaluate it? Let&#8217;s get the first 20 numbers:</p>
<pre>scala&gt; fibs take 20 foreach println
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
scala&gt;</pre>
<p>That looks right to me.</p>
<h2>WTF?</h2>
<p>Some of you may still be scratching your heads because I wasn&#8217;t terribly clear on how this actually works. How is it that each number is evaluated as needed? Well, first let&#8217;s prove that it is so. I&#8217;m going to modify the code slightly.</p>
<pre class="brush:scala">import scala.math.BigInt
lazy val fibs: Stream[BigInt] =
    BigInt(0) #::
    BigInt(1) #::
    fibs.zip(fibs.tail).map(n =&gt; {
      println("Evaluating: %s -&gt; %s".format(n._1, n._2))
      n._1 + n._2
    })</pre>
<p>Now let&#8217;s take the first 5:</p>
<pre>scala&gt; fibs take 5 foreach println
0
1
Evaluating: 0 -&gt; 1
1
Evaluating: 1 -&gt; 1
2
Evaluating: 1 -&gt; 2
3
scala&gt;</pre>
<p>And let&#8217;s take them again&#8230;</p>
<pre>scala&gt; fibs take 5 foreach println
0
1
1
2
3
scala&gt;</pre>
<p>And let&#8217;s take the first 7&#8230;</p>
<pre>scala&gt; fibs take 7 foreach println
0
1
1
2
3
Evaluating: 2 -&gt; 3
5
Evaluating: 3 -&gt; 5
8
scala&gt;</pre>
<p>Ok, so it works; things are properly evaluated in a lazy manner. But how?</p>
<h2>Why&#8230;</h2>
<p>The culprit behind this magic appears to be the interplay between the <code>Cons</code> class, the <code>StreamIterator</code> class and the <code>LazyCell</code> class:</p>
<pre class="brush:scala">final class Cons[+A](hd: A, tl: =&gt; Stream[A]) extends Stream[A]
// Note that the head is a value of type A and the tail is a by-name Stream</pre>
<pre class="brush:scala">final class StreamIterator[+A](self: Stream[A]) extends Iterator[A] {
  class LazyCell(st: =&gt; Stream[A]) {
    // Note the laziness
    lazy val v = st
  }
  private var these = new LazyCell(self)
  def next: A =
    if (isEmpty) Iterator.empty.next
    else {
      // Evaluate the laziness
      val cur = these.v
      // And the concrete value of type A
      val result = cur.head
      // Assign the next lazy cell to be the Stream in the tail
      these = new LazyCell(cur.tail)
      result
    }
}</pre>
<p>Couple that together with the recursively defined <code>zip</code> we saw earlier, and you&#8217;ve got your lazy Stream of Fibonacci numbers.</p>
<p>I love this stuff&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.derekwyatt.org/2011/07/29/understanding-scala-streams-through-fibonacci/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Functional &#8220;map&#8221; in C++</title>
		<link>http://www.derekwyatt.org/2011/07/15/functional-map-in-c/</link>
		<comments>http://www.derekwyatt.org/2011/07/15/functional-map-in-c/#comments</comments>
		<pubDate>Fri, 15 Jul 2011 16:21:31 +0000</pubDate>
		<dc:creator>Derek Wyatt</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://www.derekwyatt.org/?p=317</guid>
		<description><![CDATA[Note: This is C++0x stuff and it&#8217;s really just an investigation into some of the more obvious parts of it, including the auto keyword and lambda functions as well as working with higher kinded types (signified in C++ as template-template parameters). I&#8217;ve been doing a lot of Scala recently and have thus become quite spoiled [...]]]></description>
			<content:encoded><![CDATA[<p><b>Note:</b> This is C++0x stuff and it&#8217;s really just an investigation into some of the more obvious parts of it, including <a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Type_inference">the <code>auto</code> keyword</a> and <a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Lambda_functions_and_expressions">lambda functions</a> as well as working with <a href="http://en.wikipedia.org/wiki/Type_class">higher kinded types</a> (signified in C++ as <a href="http://www.progdoc.de/papers/ttp/psi-ttp/psi-ttp.html">template-template parameters</a>).</p>
<p>I&#8217;ve been doing a lot of Scala recently and have thus become quite spoiled by its awesomeness.  It&#8217;s made me look at C++ again with a different eye &#8211; a more <i>functional</i> eye.  I&#8217;ve been doing C++ for so long, that I forget about that functional style of programming, and I also forget just how bad C++ is at functional programming &#8211; when you&#8217;re a <a href="http://c2.com/cgi/wiki?MultiParadigmProgrammingLanguage">multi-paradigm language</a>, it&#8217;s hard to be great at all the paradigms simultaneously.</p>
<p>So, I took a stab at writing a more &#8220;functional&#8221; <code>map</code> function.  C++ provides the <code>transform</code> function template in the <i>functional</i> header file but I find it lacking because you have to pre-create the container that will be <i>mapped-to</i>.  This is an attempt at creating that inside the <code>map</code> function.</p>
<p>First, we&#8217;ll need some header files:</p>
<pre>
#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;list&gt;
#include &lt;string&gt;
#include &lt;functional&gt;
#include &lt;algorithm&gt;
#include &lt;iterator&gt;
#include &lt;boost/lexical_cast.hpp&gt;
</pre>
<p>And now we can define the function.</p>
<pre>
template &lt;typename InType,
  template &lt;typename U, typename alloc = allocator&lt;U&gt;&gt;
            class InContainer,
  template &lt;typename V, typename alloc = allocator&lt;V&gt;&gt;
            class OutContainer = InContainer,
  typename OutType = InType&gt;
OutContainer&lt;OutType&gt; mapf(const InContainer&lt;InType&gt;&amp; input,
                           function&lt;OutType(const InType&amp;)&gt; func)
{
  OutContainer&lt;OutType&gt; output;
  output.resize(input.size());
  transform(input.begin(), input.end(), output.begin(), func);
  return output;
}
</pre>
<p>The idea is that the output container may be a different type of container from the input container and the output type may also be of a different type from the input type.</p>
<p>A really simple usage of this could be:</p>
<pre>
vector&lt;int&gt; v1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
auto v2 = mapf(v1, function&lt;int(const int&amp;)&gt;([](const int&amp; i) { return i + 9; }));
</pre>
<p>The reason it&#8217;s simple is that all it does is just take a <code>vector</code> of <code>int</code>s and map it to a <code>vector</code> of <code>int</code>s.  That&#8217;s nothing flashy.</p>
<p>It&#8217;s more interesting if you do something like this:</p>
<pre>
auto v3 = mapf&lt;float, vector, list&gt;(
            mapf(
              mapf(v1, function&lt;int(const int&amp;)&gt;([](const int&amp; i) { return i + 9; })),
              function&lt;float(const int&amp;)&gt;([](const int&amp; i) {
                return i * 3.1415;
              })),
            function&lt;string(const float&amp;)&gt;([](const float&amp; i) {
              return string("\"" + lexical_cast&lt;string&gt;(i) + "\"");
            }));
</pre>
<p>This is the standard functional &#8220;chaining&#8221; we see with more fluid, immutable data structures.  Futher, it is actually returning a <code>list&lt;string&gt;</code> instead of a <code>vector&lt;string&gt;</code>.  In <a href="http://typesafe.com">Scala</a> (you could do something similar in <a href="http://ruby-lang.org">Ruby</a> or many other languages) this would be:</p>
<pre>
v1.map(_ + 9).map(_ * 3.1415).map(_.toString).toList
</pre>
<p>Now, I&#8217;m not exactly happy with what we&#8217;ve got here.  It&#8217;s not that I can&#8217;t <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=179766">pimp</a> the <code>int</code> and <code>float</code> types and thus make it more fluid (although that would be nice).  It&#8217;s more that the template function specification is hideous.  In order to actually use different output container types, you must specify too much in the template parameter list.</p>
<pre>
auto l1 = mapf&lt;int, vector, list&gt;(v1,
  function&lt;int(const int&amp;)&gt;([](const int&amp; i) { return i + 2; }));
copy(l1.begin(), l1.end(), ostream_iterator&lt;int&gt;(cout, "\n"));
</pre>
<p>Ideally we&#8217;d like to simply specify something like <code>mapf&lt;list&gt;(...)</code> instead.  I need to work on this and see if I can come up with something nicer.  Perhaps it&#8217;s as simple as wrapping it up with another function or a template class&#8230; when I get more time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.derekwyatt.org/2011/07/15/functional-map-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My Vim config is on GitHub</title>
		<link>http://www.derekwyatt.org/2011/07/05/my-vim-config-is-on-github/</link>
		<comments>http://www.derekwyatt.org/2011/07/05/my-vim-config-is-on-github/#comments</comments>
		<pubDate>Tue, 05 Jul 2011 18:09:50 +0000</pubDate>
		<dc:creator>Derek Wyatt</dc:creator>
				<category><![CDATA[Vim]]></category>

		<guid isPermaLink="false">http://derekwyatt.org/2011/07/05/my-vim-config-is-on-github/</guid>
		<description><![CDATA[I&#8217;ve put my Vim configuration on GitHub now. Have a gander at http://github.com/derekwyatt/vim-config]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve put my Vim configuration on GitHub now. Have a gander at <a href="http://github.com/derekwyatt/vim-config">http://github.com/derekwyatt/vim-config</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.derekwyatt.org/2011/07/05/my-vim-config-is-on-github/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Scala indent file for Vim</title>
		<link>http://www.derekwyatt.org/2011/03/10/scala-indent-file-for-vim/</link>
		<comments>http://www.derekwyatt.org/2011/03/10/scala-indent-file-for-vim/#comments</comments>
		<pubDate>Thu, 10 Mar 2011 15:17:30 +0000</pubDate>
		<dc:creator>Derek Wyatt</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[Vim]]></category>
		<category><![CDATA[vim scala]]></category>

		<guid isPermaLink="false">http://derekwyatt.org/2011/03/10/scala-indent-file-for-vim/</guid>
		<description><![CDATA[The Vim &#8216;indent&#8217; script for Scala that I&#8217;ve been working on is now starting to take some decent shape. If you&#8217;re a Scala coder and are working in Vim, I can now actually recommend this script :). It&#8217;s actually the least complicated one I&#8217;ve written that achieves this level of functionality; I&#8217;ve had a few [...]]]></description>
			<content:encoded><![CDATA[<p>The Vim &#8216;indent&#8217; script for Scala that I&#8217;ve been working on is now starting to take some decent shape. If you&#8217;re a Scala coder and are working in Vim, I can now actually recommend this script :). It&#8217;s actually the least complicated one I&#8217;ve written that achieves this level of functionality; I&#8217;ve had a few kicks at this particular can and one of them in particular was <b>way</b> complicated and also <em>slow</em>. </p>
<p><a href="http://github.com/ewiplayer/vim-scala"  alt="Go grab it from Github">Go grab it from Github</a>.
<p>Posted with WordPress for BlackBerry.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.derekwyatt.org/2011/03/10/scala-indent-file-for-vim/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Vim indent file for Scala has been updated</title>
		<link>http://www.derekwyatt.org/2011/03/09/vim-indent-file-for-scala-has-been-updated/</link>
		<comments>http://www.derekwyatt.org/2011/03/09/vim-indent-file-for-scala-has-been-updated/#comments</comments>
		<pubDate>Wed, 09 Mar 2011 15:44:58 +0000</pubDate>
		<dc:creator>Derek Wyatt</dc:creator>
				<category><![CDATA[Vim]]></category>
		<category><![CDATA[vim scala]]></category>

		<guid isPermaLink="false">http://derekwyatt.org/2011/03/09/vim-indent-file-for-scala-has-been-updated/</guid>
		<description><![CDATA[I found some time to update the indent file for Scala recently. It&#8217;s getting better and more complicated, unfortunately. Please feel free to fork it and make changes/fixes&#8230; I hate writing this thing :) Grab it from my vim-scala repository on github. Posted with WordPress for BlackBerry.]]></description>
			<content:encoded><![CDATA[<p>I found some time to update the indent file for Scala recently. It&#8217;s getting better and more complicated, unfortunately. Please feel free to fork it and make changes/fixes&#8230; I hate writing this thing :)</p>
<p>Grab it from <a href="http://github.com/ewiplayer/vim-scala"  alt="my vim-scala repository on github">my vim-scala repository on github</a>.
<p>Posted with WordPress for BlackBerry.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.derekwyatt.org/2011/03/09/vim-indent-file-for-scala-has-been-updated/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Started some work on Scala</title>
		<link>http://www.derekwyatt.org/2011/02/27/started-some-work-on-scala/</link>
		<comments>http://www.derekwyatt.org/2011/02/27/started-some-work-on-scala/#comments</comments>
		<pubDate>Sun, 27 Feb 2011 13:37:21 +0000</pubDate>
		<dc:creator>Derek Wyatt</dc:creator>
				<category><![CDATA[Vim]]></category>
		<category><![CDATA[vim scala]]></category>

		<guid isPermaLink="false">http://www.derekwyatt.org/2011/02/27/started-some-work-on-scala/</guid>
		<description><![CDATA[So, a little over a month ago, I changed departments where I work &#8211; I used to work in the Enterprise Software group and have moved to the System Architecture / Research group. There are some great things that go with this: I get to work with Vim more than I used to because I [...]]]></description>
			<content:encoded><![CDATA[<p>So, a little over a month ago, I changed departments where I work &#8211; I used to work in the Enterprise Software group and have moved to the System Architecture / Research group.  There are some great things that go with this:</p>
<ol>
<li>I get to work with Vim more than I used to because I now code a lot more than I used to.</li>
<li>I&#8217;ve effectively <i>deleted</i> Windows entirely and replaced it with <i>Ubuntu</i> (YAY!)</li>
<li>I&#8217;m getting a chance to deeply investigate <a href="http://scala-lang.org">Scala</a> and <a href="http://akka.io">Akka</a>, which is a real treat!  My research may not go anywhere, but the research itself is incredibly useful, I think &#8211; Scala and Akka are absolutely fantastic projects.</li>
</ol>
<p>Once I figure out the right path to take in order to get some changes into the Scala repository for Vim, I&#8217;ll do that, but for the moment I&#8217;m just having a great time banging away at the docs and shoving things in my own repository.</p>
<p>What I&#8217;ve got at the moment is a 4000+ line reference file (in Vim help format, of course) that I&#8217;ve put together to help me better understand Scala, and give me a spot to put some critical information and tips / tricks I find as I go.  I&#8217;ve also fixed up the indent file a bit and plan to enhance the syntax file when I get a chance too.</p>
<p>Because of Scala&#8217;s flexibility and terseness I find it a bit difficult to create code snippets for it, but I may do that in the future as well.</p>
<p>If you&#8217;re interested, head over to <a href="http://github.com/ewiplayer/vim-scala">my vim-scala repository on GitHub</a> and clone it down to your vim configuration.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.derekwyatt.org/2011/02/27/started-some-work-on-scala/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 2.296 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-02-05 00:33:22 -->

