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

<channel>
	<title>Heiko&#039;s Blog &#187; Scala</title>
	<atom:link href="http://hseeberger.wordpress.com/category/scala/feed/" rel="self" type="application/rss+xml" />
	<link>http://hseeberger.wordpress.com</link>
	<description>Mainly about software development</description>
	<lastBuildDate>Wed, 15 May 2013 15:00:20 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='hseeberger.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Heiko&#039;s Blog &#187; Scala</title>
		<link>http://hseeberger.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://hseeberger.wordpress.com/osd.xml" title="Heiko&#039;s Blog" />
	<atom:link rel='hub' href='http://hseeberger.wordpress.com/?pushpress=hub'/>
		<item>
		<title>SBT-Eclipse Integration</title>
		<link>http://hseeberger.wordpress.com/2011/03/31/sbt-eclipse-integration/</link>
		<comments>http://hseeberger.wordpress.com/2011/03/31/sbt-eclipse-integration/#comments</comments>
		<pubDate>Thu, 31 Mar 2011 09:56:21 +0000</pubDate>
		<dc:creator>Heiko Seeberger</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://hseeberger.wordpress.com/?p=277</guid>
		<description><![CDATA[Yay, we finally have got a really good Eclipse plugin for Scala. Thanks to all the contributors for their great work (as a former Eclipse committer I know that it was hard work). But as lots of Scala projects use &#8230; <a href="http://hseeberger.wordpress.com/2011/03/31/sbt-eclipse-integration/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hseeberger.wordpress.com&#038;blog=15073356&#038;post=277&#038;subd=hseeberger&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Yay, we finally have got a really good <a href="http://www.scala-ide.org/" target="_blank">Eclipse plugin</a> for Scala. Thanks to all the contributors for their great work (as a former Eclipse committer I know that it was hard work). But as lots of Scala projects use SBT as their build tool, a new need is arising, the need for an integration of SBT and Eclipse. For the last one and a half years or so I have been using SBT and IntelliJ IDEA, because the Scala plugin for IDEA is awesome and, most important, there is a really good SBT-IDEA integration. It is provided by the <a href="https://github.com/mpeltonen/sbt-idea" target="_blank">sbt-idea</a> project which I take as an inspiring example for what I would like to achieve for SBT-Eclipse integration.</p>
<p>Therefore I started the <a href="https://github.com/typesafehub/sbteclipse" target="_blank">sbteclipse</a> project which aims at providing the same features as sbt-idea, i.e. the ability to create Eclipse project files (<em>.project</em> and <em>.classpath</em>) from an SBT project. As SBT will soon be on version 0.9 which differs a great lot from version 0.7 from a plugin developer&#8217;s perspective, I decided to develop sbteclipse as a plugin for SBT 0.9.</p>
<p>While there is still a very long way to go, I just released the <strong>very first version 0.1</strong> of sbteclipse to the <a href="http://repo.typesafe.com/typesafe/webapp/browserepo.html?pathId=ivy-releases%3Acom.typesafe.sbteclipse" target="_blank">Typesafe repository</a> which means that you can use it easily. Right now it will only create a single project with its source- and class-directories. Libraries and multi-module projects are not yet supported. And of course you will have to <a href="http://code.google.com/p/simple-build-tool/wiki/Build" target="_blank">build SBT 0.9 on your own</a>, because there are no binaries yet.</p>
<p>If you are interested, please take a look at the &#8220;Usage&#8221; section of the <a href="https://github.com/typesafehub/sbteclipse/blob/master/README.textile" target="_blank">sbteclipse README</a>. I would be glad to get your feedback, of course. Have fun!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hseeberger.wordpress.com/277/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hseeberger.wordpress.com/277/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hseeberger.wordpress.com&#038;blog=15073356&#038;post=277&#038;subd=hseeberger&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hseeberger.wordpress.com/2011/03/31/sbt-eclipse-integration/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/3474b9b33fc7ebd2b7bf8555d45f5298?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">hseeberger</media:title>
		</media:content>
	</item>
		<item>
		<title>Applicatives are generalized functors</title>
		<link>http://hseeberger.wordpress.com/2011/01/31/applicatives-are-generalized-functors/</link>
		<comments>http://hseeberger.wordpress.com/2011/01/31/applicatives-are-generalized-functors/#comments</comments>
		<pubDate>Mon, 31 Jan 2011 10:38:05 +0000</pubDate>
		<dc:creator>Heiko Seeberger</dc:creator>
				<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://hseeberger.wordpress.com/?p=202</guid>
		<description><![CDATA[In my previous blog post about categories and functors I already threatened you with the possibility of a follow-up. Well, here we go. Actually I won&#8217;t talk about category theory this time, but about an important abstraction from the world &#8230; <a href="http://hseeberger.wordpress.com/2011/01/31/applicatives-are-generalized-functors/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hseeberger.wordpress.com&#038;blog=15073356&#038;post=202&#038;subd=hseeberger&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In my <a href="https://hseeberger.wordpress.com/2010/11/25/introduction-to-category-theory-in-scala/">previous blog post</a> about categories and functors I already threatened you with the possibility of a follow-up. Well, here we go. Actually I won&#8217;t talk about category theory this time, but about an important abstraction from the world of advanced (at least in my understanding) functional programming which turns out to be a close relative to the now well understood functor.</p>
<h2>Functors</h2>
<p>Just in case you don&#8217;t remember exactly what a functor looks like, here comes the definition:</p>
<pre class="brush: scala; title: ; notranslate">
trait GenericFunctor[-&gt;&gt;[_, _], -&gt;&gt;&gt;[_, _], F[_]] {

  def fmap[A, B](f: A -&gt;&gt; B): F[A] -&gt;&gt;&gt; F[B]
}

trait Functor[F[_]] extends GenericFunctor[Function, Function, F] {

  final def fmap[A, B](as: F[A])(f: A =&gt; B): F[B] =
    fmap(f)(as)
}
</pre>
<p>For the sake of simplicity we will stick to the more specific <em>Functor</em> definition throughout the rest of this post. Such a functor is an endofunctor, because its source and target are the same (the category of Scala types and Scala functions). Maybe you remember that such a functor can be regarded as a provider of a computational context: The function <em>f: A =&gt; B</em> you give to <em>fmap</em> is lifted into the functor&#8217;s context which means that it is executed (maybe once, maybe several times or maybe even not at all) under the control of the functor.</p>
<p><a href="http://hseeberger.files.wordpress.com/2011/01/functor3.png"><img class="alignnone size-full wp-image-257" title="Mapping an arity-1 function" src="http://hseeberger.files.wordpress.com/2011/01/functor3.png?w=640" alt=""   /></a></p>
<p>As an example let&#8217;s look at how the <em>OptionFunctor</em> defined in the <a href="https://hseeberger.wordpress.com/2010/11/25/introduction-to-category-theory-in-scala/">previous blog post</a> is working: If we give <em>fmap</em> a <em>Some</em> the given function will be invoked, if we give it a <em>None</em> it won&#8217;t be invoked.</p>
<pre class="brush: scala; title: ; notranslate">
scala&gt; fmap(Option(1)) { x =&gt; println(&quot;I was invoked!&quot;); x + 1 }
I was invoked!
res0: Option[Int] = Some(2)

scala&gt; fmap(None: Option[Int]) { x =&gt; println(&quot;I was invoked!&quot;); x + 1 }
res1: Option[Int] = None
</pre>
<p>So far, so good. Using functors we can lift functions of <strong>arity-1</strong> into a computational context.</p>
<h2>Applicatives</h2>
<p>But what if we have a function of higher arity? Can we still use a functor to lift a function of, let&#8217;s say, <strong>arity-2</strong>?</p>
<p><a href="http://hseeberger.files.wordpress.com/2011/01/applicative1.png"><img class="alignnone size-full wp-image-258" title="Mapping an arity-2 function" src="http://hseeberger.files.wordpress.com/2011/01/applicative1.png?w=640" alt=""   /></a></p>
<p>Let&#8217;s look at what happens if we call <em>fmap</em> to partially apply an arity-2 function to its first argument within the computational context of an <em>Option</em>:</p>
<pre class="brush: scala; title: ; notranslate">
scala&gt; val f = (x: Int) =&gt; (y: Int) =&gt; x + y + 10
f: (Int) =&gt; (Int) =&gt; Int = &lt;function1&gt;

scala&gt; fmap(Option(1))(f)
res0: Option[(Int) =&gt; Int] = Some()
</pre>
<p>What we get back is an <em>Option[Int =&gt; Int]</em>, i.e. the &#8220;rest&#8221; of the partially applied function wrapped in an <em>Option</em>. Now we have a problem, because we cannot give this lifted function to another call of <em>fmap</em>.</p>
<pre class="brush: scala; title: ; notranslate">
scala&gt; fmap(Option(2))(fmap(Option(1))(f))
:13: error: type mismatch;
 found   : Option[(Int) =&gt; Int]
 required: (Int) =&gt; ?
       fmap(Option(2))(fmap(Option(1))(f))
</pre>
<p>Of course we cannot, because <em>fmap</em> expects a pure function, not a lifted one. And that&#8217;s the moment when applicatives enter the stage. The idea is simple and follows intutively from what we have just seen: Instead of <em>fmap</em> taking a pure function, an <em>Applicative</em> defines the method <em>apply</em> taking a lifted function. And it defines the method <em>pure</em> to lift pure functions. Using these it is perfectly possible to partially apply an arity-n function to all of its arguments within a computational context. Before we look at our example from this new perspective, let&#8217;s code up our new abstraction:</p>
<pre class="brush: scala; title: ; notranslate">
trait Applicative[F[_]] extends Functor[F] {

  def pure[A](a: A): F[A]

  def apply[A, B](f: F[A =&gt; B]): F[A] =&gt; F[B]

  final def apply[A, B](fa: F[A])(f: F[A =&gt; B]): F[B] =
    apply(f)(fa)

  override def fmap[A, B](f: A =&gt; B): F[A] =&gt; F[B] =
    apply(pure(f))
}
</pre>
<p>As you can see, there is a strong relation between functors and applicatives: Each applicative is a functor and by one of the laws for applicatives the following has to hold true: <em>fmap = apply ο pure</em>. Well, this law is pretty intuitive, because it makes sure we can use an applicative as a functor, i.e. for a pure arity-1 function, and it will behave as expected.</p>
<p>In order to be able to work with applicatives we need some scaffolding and for our <em>Option</em> example we need an implementation of <em>Applicative</em>:</p>
<pre class="brush: scala; title: ; notranslate">
object Applicative {

  def pure[A, F[_]](a: A)(implicit applicative: Applicative[F]): F[A] =
    applicative pure a

  def apply[A, B, F[_]](fa: F[A])(f: F[A =&gt; B])(implicit applicative: Applicative[F]): F[B] =
    applicative.apply(fa)(f)

  implicit object OptionApplicative extends Applicative[Option] {

    override def pure[A](a: A): Option[A] =
      Option(a)

    override def apply[A, B](f: Option[A =&gt; B]): Option[A] =&gt; Option[B] =
      o =&gt; for { a &lt;- o; p &lt;- f } yield p(a)
    }
}
</pre>
<p>Now let&#8217;s look at our example from above with an arity-2 function. Using a functor we got stuck, but using an applicative we can make it all the way through the two arguments:</p>
<pre class="brush: scala; title: ; notranslate">
scala&gt; apply(Option(1))(apply(Option(2))(pure(f)))
res0: Option[Int] = Some(13)
</pre>
<p>Ain&#8217;t that nice? You might answer, that this code looks cumbersome and is not necessary at all. Regarding the first argument please read on. Regarding the second: Yes, of course we don&#8217;t need an applicative for <em>Option</em>, because it already offers <em>flatMap</em> which does the job. But with this type class approach we can deal with any class, e.g. with <em>Either</em> from the Scala standard library or with classes from our own projects.</p>
<h2>Conclusion</h2>
<p>You have seen the basic principle of applicatives: We can apply functions of arbitrary arity (well, greater or even one) to its arguments within a computational context. As functors provide exactly this for arity-1, applicatives are generalized functors.</p>
<p>Thanks to Scala&#8217;s flexibility we can of course do much better than above. Using a little pimp my library and some operators we can get something that&#8217;s elegant and useful. Luckily the <a href="http://code.google.com/p/scalaz/">scalaz</a> folks have already done this, so I will just show two ways of expressing the above example using this awesome library:</p>
<pre class="brush: scala; title: ; notranslate">
scala&gt; Option(1) &lt;*&gt; (Option(2) &lt;*&gt; Option(f))
res0: Option[Int] = Some(13)

scala&gt; (Option(1) &lt;**&gt; Option(2)) { _ + _ + 10 }
res1: Option[Int] = Some(13)
</pre>
<p>Now this is really nice, isn&#8217;t it? Especially the second one looks very concise and intuitive. And as I stated above we can use it for types that don&#8217;t bring helpful methods like <em>flatMap</em>. Let&#8217;s conclude with another example using <em>Either</em> which is a perfect candidate to be used for results that might fail with well defined errors:</p>
<pre class="brush: scala; title: ; notranslate">
scala&gt; (1.right[String] &lt;**&gt; 2.right[String]) { _ + _ + 10 }     
res0: Either[String,Int] = Right(13)

scala&gt; (1.right[String] &lt;**&gt; &quot;Error&quot;.left[Int]) { _ + _ + 10 }
res1: Either[String,Int] = Left(Error)
</pre>
<p>If you are interested in the code examples shown above, you can find these here: <a href="https://github.com/weiglewilczek/fun">https://github.com/weiglewilczek/fun</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hseeberger.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hseeberger.wordpress.com/202/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hseeberger.wordpress.com&#038;blog=15073356&#038;post=202&#038;subd=hseeberger&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hseeberger.wordpress.com/2011/01/31/applicatives-are-generalized-functors/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/3474b9b33fc7ebd2b7bf8555d45f5298?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">hseeberger</media:title>
		</media:content>

		<media:content url="http://hseeberger.files.wordpress.com/2011/01/functor3.png" medium="image">
			<media:title type="html">Mapping an arity-1 function</media:title>
		</media:content>

		<media:content url="http://hseeberger.files.wordpress.com/2011/01/applicative1.png" medium="image">
			<media:title type="html">Mapping an arity-2 function</media:title>
		</media:content>
	</item>
		<item>
		<title>Introduction to Category Theory in Scala</title>
		<link>http://hseeberger.wordpress.com/2010/11/25/introduction-to-category-theory-in-scala/</link>
		<comments>http://hseeberger.wordpress.com/2010/11/25/introduction-to-category-theory-in-scala/#comments</comments>
		<pubDate>Thu, 25 Nov 2010 13:00:00 +0000</pubDate>
		<dc:creator>Heiko Seeberger</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://hseeberger.wordpress.com/?p=58</guid>
		<description><![CDATA[If you are a former Java developer and have become a Scala fanboy like me, you will probably sooner or later encounter terms like monad, functor or other mysteries from the realm of category theory which make you feel like &#8230; <a href="http://hseeberger.wordpress.com/2010/11/25/introduction-to-category-theory-in-scala/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hseeberger.wordpress.com&#038;blog=15073356&#038;post=58&#038;subd=hseeberger&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>If you are a former Java developer and have become a Scala fanboy like me, you will probably sooner or later encounter terms like monad, functor or other mysteries from the realm of category theory which make you feel like a little dummkopf (screamingly funny for a German like me, according to <a href="http://www.dict.cc/">www.dict.cc</a> this seems to be a proper English verb). If you already feel comfortable with these, don&#8217;t waste your time and move along. But if not, I would like to invite you to a little sightseeing trip that reflects my efforts to get to know this secret realm somewhere in between abstract mathematics and computer science.</p>
<p>This blog post is meant to be an introduction. Depending on the effect on my health (while writing I&#8217;m often afraid that my head might explode), my future spare time (understanding comes very slowly, if at all) and your feedback, I am going to write a follow-up. But for now let&#8217;s get started.</p>
<h2>What&#8217;s a category?</h2>
<p>Obviously this should be the first question when talking about category theory, although in my opinion the concept of a category is not too useful for programming. Here comes a comprehensive answer:</p>
<p>A <strong>category</strong> is made up from <strong>objects</strong> and <strong>maps</strong> (aka morphisms or arrows) between these objects. Maps can be <strong>composed</strong> in an <strong>associative</strong> fashion and for each object there is an <strong>identity map</strong> which is neutral with regard to composition.</p>
<p>Objects can be anything, but let&#8217;s look at a simple case: The category of finite sets. The diagram below depicts two such finite sets as well as a map from the one called source (aka domain) to the other called target (aka codomain).</p>
<p><a href="http://hseeberger.files.wordpress.com/2010/11/finite-sets2.png"><img class="alignnone size-full wp-image-112" title="Example of finite sets with a map" src="http://hseeberger.files.wordpress.com/2010/11/finite-sets2.png?w=640" alt=""   /></a></p>
<p>A little more formally, we can call the domain A and the codomain B and write the map like this:</p>
<p>f: A → B</p>
<p>Now what&#8217;s composition? Let&#8217;s look at the next diagram, where I added another finite set and another map. Please don&#8217;t worry that in this strange world eating habits are different from what you might know <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p><a href="http://hseeberger.files.wordpress.com/2010/11/composition2.png"><img class="alignnone size-full wp-image-111" title="Example of composition of maps" src="http://hseeberger.files.wordpress.com/2010/11/composition2.png?w=640" alt=""   /></a></p>
<p>Let&#8217;s call the new set C and the new map g: B → C. Obviously we can get from A to C by first following f and then g. Therefore we get a new map from composing f and g:</p>
<p>g ο f: A → C</p>
<p>Now that we know composition, we have to talk about associativity and identity. Let&#8217;s add another map h: C → D. Then the associativity law requires the following to hold true:</p>
<p>(h ο g) ο f = h ο (g ο f)</p>
<p>Associativity should become clear pretty fast from thinking of addition or multiplication of numbers. Therefore let&#8217;s move along towards the identity laws. These require that for each object X of the category there is an identity map 1<sub>X</sub>: X → X which satisfies the following rules:</p>
<ul>
<li>f ο 1<sub>A</sub> = f</li>
<li>1<sub>B</sub> ο f = f</li>
</ul>
<p>The following diagram depicts an identity map in our example category of finite sets. Obviously for identity maps the domain and codomain are the same object.</p>
<p><a href="http://hseeberger.files.wordpress.com/2010/11/identity.png"><img class="alignnone size-full wp-image-119" title="An example for an identity map" src="http://hseeberger.files.wordpress.com/2010/11/identity.png?w=640" alt=""   /></a></p>
<p>OK, that&#8217;s it. That&#8217;s categories. Objects, maps, composition, associativity and identity. If you would like to dive a little deeper into the theory, I recommend <a href="http://en.wikipedia.org/wiki/Category_theory#Categories.2C_objects.2C_and_morphisms">Wikipedia</a> or <a href="http://www.cambridge.org/gb/knowledge/isbn/item1165069/?site_locale=en_GB">&#8220;Conceptual Mathematics&#8221; by Lawvere and Schanuel</a>. I will move along and look at categories from a Scala point of view.</p>
<h2>Categories in Scala</h2>
<p>Note: In the following I will borrow a lot of ideas and even some (slightly modified) code from the <a href="https://github.com/scalaz/scalaz">scalaz</a> project. This Scala library, together with the <a href="http://apocalisp.wordpress.com/">Apocalisp</a> blog, provides an incredibly valuable source of information and inspiration about advanced functional programming in Scala.</p>
<p>Now that we have investigated the category of finite sets, let&#8217;s implement another one in Scala. Therefore we consider the category made up from Scala types as objects and Scala functions as maps. We still have to prove that this is a category, but first let&#8217;s code it up:</p>
<pre class="brush: scala; title: ; notranslate">
object Category {
  def id[A]: A =&gt; A = a =&gt; a
  def compose[A, B, C](g: B =&gt; C, f: A =&gt; B): A =&gt; C =
    g compose f // This is Function.compose, not a recursive call!
}
</pre>
<p>OK, it looks like we have all the ingredients we need: Types are objects, functions with one argument (trait <em>Function</em>) are maps, <em>id</em> returns the identity function for each <em>A</em> and <em>compose</em> composes two functions.</p>
<p>It looks obvious, that the associativity and identity laws are satisfied, but better let&#8217;s check using a simple unit test written using the awesome <a href="http://code.google.com/p/specs/">specs</a> and <a href="http://code.google.com/p/scalacheck/">ScalaCheck</a> frameworks:</p>
<pre class="brush: scala; title: ; notranslate">
class CategorySpec extends Specification with ScalaCheck {
  import Category._

  &quot;A Category&quot; should {

    val f = (i: Int) =&gt; i.toString
    val g = (s: String) =&gt; s.length
    val h = (i: Int) =&gt; i * i

    &quot;satisfy associativity&quot; in {
      Prop forAll { (i: Int) =&gt;
        compose(h, compose(g, f))(i) == compose(compose(h, g), f)(i)
      } must pass
    }

    &quot;satisfy identity&quot; in {
      Prop forAll { (i: Int) =&gt;
        compose(f, id[Int])(i) mustEqual compose(id[String], f)(i)
      } must pass
    }
  }
}
</pre>
<p>OK, so now we know that <em>Category</em> indeed adheres to the category laws. But that&#8217;s not the end of our story! Let&#8217;s move along to a more general category in Scala: While sticking to the Scala types as objects we will use the type constructor <em>-&gt;&gt;</em> for the maps.</p>
<pre class="brush: scala; title: ; notranslate">
trait GenericCategory[-&gt;&gt;[_, _]] {
  def id[A]: A -&gt;&gt; A
  def compose[A, B, C](g: B -&gt;&gt; C, f: A -&gt;&gt; B): A -&gt;&gt; C
}
</pre>
<p>Please note, that <em>A -&gt;&gt; B</em> is just another way to write <em>-&gt;&gt;[A, B]</em>, which nicely reflects the fact that we are talking about maps here.</p>
<p>Of course our <em>Category</em> is an implementation of this <em>GenericCategory</em>:</p>
<pre class="brush: scala; title: ; notranslate">
object Category extends GenericCategory[Function] {
  def id[A]: A =&gt; A = a =&gt; a
  def compose[A, B, C](g: B =&gt; C, f: A =&gt; B): A =&gt; C =
    g compose f // This is Function.compose, not a recursive call!
}
</pre>
<p>If you are interested in further types of categories, don&#8217;t hesitate to take a look at <a href="https://github.com/scalaz/scalaz">scalaz</a>: You can find numerous categories there, e.g. a category of partial functions or a monoid category. I will keep it that way and move along to another important concept in category theory.</p>
<h2>Functors</h2>
<p>Now that we know categories and how to represent certain ones in Scala, let&#8217;s look at another important concept of category theory, which is also very important for functional programming. Consider two categories C1 and C2; then a <strong>functor</strong> F is a <strong>structure-preserving</strong> mapping between these categories.</p>
<p>OK, but what does that mean? A mapping between categories simply means that</p>
<ul>
<li>every object A &isin; C1 is mapped to to an object F(A) &isin; C2 and</li>
<li>every map A → B between two objects A, B &isin; C1 is mapped to a map F(A) → F(B) between two objects F(A), F(B) &isin; C2.</li>
</ul>
<p>In order to preserve the category structure this mapping must preserve the identity maps and the compositions. More formally:</p>
<ul>
<li>F(1<sub>A</sub>) = 1<sub>F(A)</sub> &forall; A &isin; C1</li>
<li>F(g ο f) = F(g) ο F(f)</sub> &forall; f: A → B, g: B → C where A, B, C &isin; C1</li>
</ul>
<p>Before thinking about the &#8220;meaning&#8221; of a functor, let&#8217;s code it up in Scala using our <em>GenericCategory</em> (of Scala types and arbitrary maps between these) as foundation:</p>
<pre class="brush: scala; title: ; notranslate">
trait GenericFunctor[-&gt;&gt;[_, _], -&gt;&gt;&gt;[_, _], F[_]] {
  def fmap[A, B](f: A -&gt;&gt; B): F[A] -&gt;&gt;&gt; F[B]
}
</pre>
<p>Again, <em>-&gt;&gt;</em> and <em>-&gt;&gt;&gt;</em> as well as <em>F</em> are type constructors. Looking at the ingredients, we find all that we need: Types <em>A</em> and <em>B</em> are mapped to types <em>F[A]</em> and <em>F[B]</em> and maps A<em> -&gt;&gt; B</em> are mapped to maps <em>F[A] -&gt;&gt;&gt; F[B]</em>.</p>
<p>Now let&#8217;s move along from arbitrary maps to Scala functions, i.e. choose our <em>Category</em> as source and target of the functor. This results in a so called endofunctor (same source and target) and looks like the following:</p>
<pre class="brush: scala; title: ; notranslate">
trait Functor[F[_]] extends GenericFunctor[Function, Function, F] {
  final def fmap[A, B](as: F[A])(f: A =&gt; B): F[B] =
    fmap(f)(as)
}
</pre>
<p>Please note, that the new <em>fmap</em> method is just for convenience and delegates to the inherited one. Using the higher kinded type for the first parameter list makes it possible to infer the type of <em>A</em> for the function in the second parameter list.</p>
<p>In order to code up some examples, we have to specify the type constructor <em>F</em>. Let&#8217;s start with good old <em>List</em>:</p>
<pre class="brush: scala; title: ; notranslate">
object ListFunctor extends Functor[List] {
  def fmap[A, B](f: A =&gt; B): List[A] =&gt; List[B] = as =&gt; as map f
}
</pre>
<p>This one let&#8217;s us map a function over a <em>List</em>, which means that this functor looks like a container that allows us to apply a function to all of its elements. This is a very intuitive way to think about functors. And it makes clear, that functors are a very important concept for functional programming, because if you look at the collections of the Scala library, you will see, that all of them provide this &#8220;mapping a function over the elements&#8221;.</p>
<p>OK, let&#8217;s see how we can use that. Therefore we add a <em>Functor</em> object, move our <em>ListFunctor</em> into that and make it implicit and add a generic <em>fmap</em> method:</p>
<pre class="brush: scala; title: ; notranslate">
object Functor {

  def fmap[A, B, F[_]](as: F[A])(f: A =&gt; B)(implicit functor: Functor[F]): F[B] =
    functor.fmap(as)(f)

  implicit object ListFunctor extends Functor[List] {
    def fmap[A, B](f: A =&gt; B): List[A] =&gt; List[B] =
      as =&gt; as map f
  }
}
</pre>
<p>Welcome type classes! The new generic <em>fmap</em> method takes an additional and implicit parameter of type <em>Functor</em> parameterized with a higher kinded type. When we call this method with an instance of this higher kinded type and a function but no functor, the compiler will look for a matching implicit value. Let&#8217;s see it in action:</p>
<pre class="brush: scala; title: ; notranslate">
scala&gt; import com.weiglewilczek.cats.Functor._
import com.weiglewilczek.cats.Functor._

scala&gt; fmap(List(1, 2, 3))(x =&gt; x + 1)        
res0: List[Int] = List(2, 3, 4)
</pre>
<p>While we could have reached the same result by simply calling <em>map</em> on the <em>List</em> instance, we now have something more general: A <em>fmap</em> method that works for any type for which we provide a functor.</p>
<p>We still have to verify that our <em>ListFunctionFunctor</em> satisfies the functor laws. Hence we write another unit test:</p>
<pre class="brush: scala; title: ; notranslate">
class ListFunctorTest extends Specification with ScalaCheck {
  import Functor.ListFunctor._

  &quot;A ListFunctor&quot; should {

    &quot;preserve identity&quot; in {
      val stringID = (s: String) =&gt; s
      val stringListID = (ss: List[String]) =&gt; ss
      Prop forAll { (ss: List[String]) =&gt;
        fmap(stringID)(ss) == stringListID(ss)
      } must pass
    }

    &quot;preserve composition&quot; in {
      val f = (i: Int) =&gt; i.toString
      val g = (s: String) =&gt; s.length
      Prop forAll { (is: List[Int]) =&gt;
        fmap(g compose f)(is) == (fmap(g) compose fmap(f))(is)
      } must pass
    }
  }
}
</pre>
<p>Fine! Now let&#8217;s look at another example. Why not use <em>Option</em> as type constructor for the <em>Functor</em> trait?</p>
<pre class="brush: scala; title: ; notranslate">
implicit object OptionFunctor extends Functor[Option] {
  def fmap[A, B](f: A =&gt; B): Option[A] =&gt; Option[B] =
    o =&gt; o map f
}
</pre>
<p>This one let&#8217;s us map a function over an <em>Option</em>, which can be thought of as applying the function in the context of the <em>Option</em>. If it is <em>None</em>, the function won&#8217;t be applied, if it is <em>Some</em>, it will be applied. This &#8220;computational context&#8221; is another way of looking at functors which sometimes is called &#8220;lifting&#8221; of functions: The function is lifted from its normal context to the functor&#8217;s context.</p>
<p>Let&#8217;s code up another example that makes this interpretation even more obvious. Now we use <em>Function0</em> as type constructor for the <em>Functor</em> trait:</p>
<pre class="brush: scala; title: ; notranslate">
implicit object Function0Functor extends Functor[Function0] {
  def fmap[A, B](f: A =&gt; B): Function0[A] =&gt; Function0[B] =
    a =&gt; () =&gt; f(a())
}
</pre>
<p>Let&#8217;s see this one in action:</p>
<pre class="brush: scala; title: ; notranslate">
scala&gt; val f = (s: String) =&gt; s.length
f: (String) =&gt; Int = &lt;function1&gt;

scala&gt; val lifted = fmap(() =&gt; &quot;abc&quot;)(f)
lifted: () =&gt; Int = &lt;function0&gt;

scala&gt; lifted()
res1: Int = 3
</pre>
<p>As you can see, the function <em>f</em> is lifted into the context of the given <em>Function0</em>, i.e. it works on the output of that.</p>
<h2>Conclusion</h2>
<p>In this blog post we looked at two basic objects from category theory: Categories and functors. Of course there are others, some of them heavily used (e.g. monads), but I will keep it like that for now. Hopefully I could show you that category theory offers some interesting and valuable concepts that can be applied to and expressed in Scala. As I consider myself still a rookie in category theory, I&#8217;d be happy to get your feedback.</p>
<p>If you are interested in the code examples shown above, you can find these here: <a href="https://github.com/weiglewilczek/fun">https://github.com/weiglewilczek/fun</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hseeberger.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hseeberger.wordpress.com/58/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hseeberger.wordpress.com&#038;blog=15073356&#038;post=58&#038;subd=hseeberger&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hseeberger.wordpress.com/2010/11/25/introduction-to-category-theory-in-scala/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/3474b9b33fc7ebd2b7bf8555d45f5298?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">hseeberger</media:title>
		</media:content>

		<media:content url="http://hseeberger.files.wordpress.com/2010/11/finite-sets2.png" medium="image">
			<media:title type="html">Example of finite sets with a map</media:title>
		</media:content>

		<media:content url="http://hseeberger.files.wordpress.com/2010/11/composition2.png" medium="image">
			<media:title type="html">Example of composition of maps</media:title>
		</media:content>

		<media:content url="http://hseeberger.files.wordpress.com/2010/11/identity.png" medium="image">
			<media:title type="html">An example for an identity map</media:title>
		</media:content>
	</item>
	</channel>
</rss>
