<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0"><id>tag:blogger.com,1999:blog-22587889</id><updated>2013-05-23T12:19:09.483+05:30</updated><category term="ruby" /><category term="couchdb" /><category term="amqp" /><category term="javascript" /><category term="clojure" /><category term="erlang" /><category term="web" /><category term="websocket" /><category term="redis" /><category term="monad" /><category term="data-structures" /><category term="actor" /><category term="lookback" /><category term="OCaml" /><category term="smullyan" /><category term="mina" /><category term="terracotta" /><category term="open source" /><category term="mustang" /><category term="RIA" /><category term="eventsourcing" /><category term="combinator" /><category term="guice" /><category term="agile" /><category term="dslsina" /><category term="yegge" /><category term="spring" /><category term="rails" /><category term="functional" /><category term="haskell" /><category term="api programming" /><category term="datatype-generic-programming" /><category term="cqrs" /><category term="nosql" /><category term="map-reduce" /><category term="inductive" /><category term="database" /><category term="corecursion" /><category term="message-queue" /><category term="xml" /><category term="scala" /><category term="scouchdb" /><category term="type" /><category term="java" /><category term="scalability" /><category term="seam" /><category term="ajax" /><category term="patterns" /><category term="mixin" /><category term="programming" /><category term="jpa-gotcha-series" /><category term="aop" /><category term="rants" /><category term="demeter" /><category term="stm" /><category term="knuth" /><category term="lisp" /><category term="F#" /><category term="algorithm" /><category term="OO" /><category term="jvm" /><category term="category_theory" /><category term="joy" /><category term="concurrency" /><category term="lift" /><category term="DI" /><category term="rest" /><category term="oscon08" /><category term="potpouri" /><category term="algebra" /><category term="fixpoint" /><category term="ddd" /><category term="scalaz" /><category term="euler" /><category term="groovy" /><category term="jpa" /><category term="software" /><category term="orm" /><category term="closure" /><category term="dao" /><category term="dsl" /><category term="parser-combinator" /><category term="memcached" /><category term="akka" /><category term="design" /><category term="testing" /><category term="json" /><category term="potpourri" /><title type="text">Ruminations of a Programmer</title><subtitle type="html">A programmer's blog - will deal with everything that relates to a programmer. Occasionally, it will contain some humour, some politics and some sport news.</subtitle><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://debasishg.blogspot.com/feeds/posts/full" /><link rel="alternate" type="text/html" href="http://debasishg.blogspot.com/" /><link rel="next" type="application/atom+xml" href="http://debasishg.blogspot.com/feeds/posts/full?start-index=4&amp;max-results=3" /><author><name>Debasish Ghosh</name><uri>https://plus.google.com/106871002817915335660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh4.googleusercontent.com/-JUSCd5diPuU/AAAAAAAAAAI/AAAAAAAABuo/RF-pdPiR7gE/s512-c/photo.jpg" /></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>300</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>3</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/RuminationsOfAProgrammer" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="ruminationsofaprogrammer" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><entry><id>tag:blogger.com,1999:blog-22587889.post-8500761222734440572</id><published>2013-03-04T11:00:00.000+05:30</published><updated>2013-03-04T11:00:02.367+05:30</updated><title type="text">An exercise in Refactoring - Playing around with Monoids and Endomorphisms</title><content type="html">A language is powerful when it offers sufficient building blocks for library design and adequate syntactic sugar that helps build expressive syntax on top of the lower level APIs that the library publishes. In this post I will discuss an exercise in refactoring while trying to raise the level of abstraction of a modeling problem. &lt;br /&gt;&lt;br /&gt;Consider the following modeling problem that I recently discussed in one of the Scala training sessions. It's simple but offers ample opportunities to explore how we can raise the level of abstraction in designing the solution model. We will start with an imperative solution and then incrementally work on raising the level of abstraction to make the final code functional and more composable.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;&lt;i&gt;A Problem of Transformation ..&lt;/I&gt;&lt;/B&gt;&lt;br /&gt;&lt;br /&gt;The problem is to compute the salary of a person through composition of multiple salary components calculated based on some percentage of other components. It's a problem of applying repeated transformations to a pipeline of successive computations - hence it can be generalized as a case study in function composition. But with some constraints as we will see shortly.&lt;br /&gt;&lt;br /&gt;Let's say that the salary of a person is computed as per the following algorithm :&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;li&gt;basic = the basic component of his salary&lt;/LI&gt;&lt;li&gt;allowances = 20% of basic&lt;/LI&gt;&lt;li&gt;bonus = 10% of (basic + allowances)&lt;/LI&gt;&lt;li&gt;tax = 30% of (basic + allowances + bonus)&lt;/LI&gt;&lt;li&gt;surcharge = 10% of (basic + allowances + bonus - tax)&lt;/LI&gt; &lt;/OL&gt;Note that the computation process starts with a basic salary, computes successive components taking the input from the previous computation of the pipeline. But there's a catch though, which makes the problem a bit more interesting from the modleing perspective. Not all components of the salary are mandatory - of course the &lt;i&gt;basic&lt;/I&gt; is mandatory. Hence the final components of the salary will be determined by a configuration object which can be like the following ..&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;// an item = true means the component should be activated in the computation&lt;br /&gt;case class SalaryConfig(&lt;br /&gt;  surcharge: Boolean    = true, &lt;br /&gt;  tax: Boolean          = true, &lt;br /&gt;  bonus: Boolean        = true,&lt;br /&gt;  allowance: Boolean    = true &lt;br /&gt;)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;So when we compute the salary we need to take care of this configuration object and activate the relevant components for calculation.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;&lt;i&gt;A Function defines a Transformation ..&lt;/I&gt;&lt;/B&gt;&lt;br /&gt;&lt;br /&gt;Let's first translate the above components into separate Scala functions ..&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;// B = basic + 20%&lt;br /&gt;val plusAllowance = (b: Double) =&gt; b * 1.2&lt;br /&gt;&lt;br /&gt;// C = B + 10%&lt;br /&gt;val plusBonus = (b: Double) =&gt; b * 1.1&lt;br /&gt;&lt;br /&gt;// D = C - 30%&lt;br /&gt;val plusTax = (b: Double) =&gt; 0.7 * b&lt;br /&gt;&lt;br /&gt;// E = D - 10%&lt;br /&gt;val plusSurcharge = (b: Double) =&gt; 0.9 * b&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Note that every function computes the salary up to the stage which will be fed to the next component computation. So the final salary is really the chained composition of all of these functions &lt;i&gt;in a specific order&lt;/I&gt; as determined by the above stated algorithm.&lt;br /&gt;&lt;br /&gt;But we need to selectively activate and deactivate the components depending on the &lt;code&gt;SalaryConfig&lt;/CODE&gt; passed. Here's the version that comes straight from the imperative mindset ..&lt;br /&gt;&lt;br /&gt;&lt;b&gt;&lt;i&gt;The Imperative Solution ..&lt;/I&gt;&lt;/B&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;// no abstraction, imperative, using var&lt;br /&gt;def computeSalary(sc: SalaryConfig, basic: Double) = {&lt;br /&gt;  var salary = basic&lt;br /&gt;  if (sc.allowance) salary = plusAllowance(salary)&lt;br /&gt;  if (sc.bonus) salary = plusBonus(salary)&lt;br /&gt;  if (sc.tax) salary = plusTax(salary)&lt;br /&gt;  if (sc.surcharge) salary = plusSurcharge(salary)&lt;br /&gt;  salary&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Straight, imperative, mutating (using var) and finally rejected by our functional mindset.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;&lt;i&gt;Thinking in terms of Expressions and Composition ..&lt;/I&gt;&lt;/B&gt;&lt;br /&gt;&lt;br /&gt;Think in terms of expressions (not statements) that compose. We have functions defined above that we could compose together and get the result. But, but .. the config, which we somehow need to incorporate as part of our composable expressions.&lt;br /&gt;&lt;br /&gt;So direct composition of functions won't work because we need some conditional support to take care of the config. How else can we have a chain of functions to compose ?&lt;br /&gt;&lt;br /&gt;Note that all of the above functions for computing the components are of type &lt;code&gt;(Double =&gt; Double)&lt;/CODE&gt;. Hmm .. this means they are &lt;i&gt;endomorphisms&lt;/I&gt;, which are functions that have the same argument and return type - &lt;i&gt;"endo"&lt;/I&gt; means &lt;i&gt;"inside"&lt;/I&gt; and &lt;i&gt;"morphism"&lt;/I&gt; means &lt;i&gt;"transformation"&lt;/I&gt;. So an endomorphism maps a type on to itself. &lt;a HREF="https://github.com/scalaz/scalaz"&gt;Scalaz&lt;/A&gt; defines it as ..&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;sealed trait Endo[A] {&lt;br /&gt;  /** The captured function. */&lt;br /&gt;  def run: A =&gt; A&lt;br /&gt;  //..&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;But the interesting part is that there's a monoid instance for &lt;code&gt;Endo&lt;/CODE&gt; and the associative &lt;code&gt;append&lt;/CODE&gt; operation of the monoid for &lt;code&gt;Endo&lt;/CODE&gt; is &lt;i&gt;function composition&lt;/I&gt;. That seems mouthful .. so let's dissect what we just said ..&lt;br /&gt;&lt;br /&gt;As you all know, a monoid is defined as "a semigroup with an identity", i.e.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;trait Monoid[A] {&lt;br /&gt;  def append(m1: A, m2: A): A&lt;br /&gt;  def zero: A&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;and &lt;code&gt;append&lt;/CODE&gt; has to be associative.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;Endo&lt;/CODE&gt; forms a monoid where &lt;code&gt;zero&lt;/CODE&gt; is the identity endomorphism and &lt;code&gt;append&lt;/CODE&gt; composes the underlying functions. Isn't that what we need ? Of course we need to figure out how to sneak in those conditionals ..&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;implicit def endoInstance[A]: Monoid[Endo[A]] = new Monoid[Endo[A]] {&lt;br /&gt;  def append(f1: Endo[A], f2: =&gt; Endo[A]) = f1 compose f2&lt;br /&gt;  def zero = Endo.idEndo&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;But we need to &lt;code&gt;append&lt;/CODE&gt; the &lt;code&gt;Endo&lt;/CODE&gt; only if the corresponding bit in &lt;code&gt;SalaryConfig&lt;/CODE&gt; is true. Scala allows extending a class with custom methods and scalaz gives us the following as an extension method on &lt;code&gt;Boolean&lt;/CODE&gt; ..&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;/**&lt;br /&gt; * Returns the given argument if this is `true`, otherwise, the zero element &lt;br /&gt; * for the type of the given argument.&lt;br /&gt; */&lt;br /&gt;final def ??[A](a: =&gt; A)(implicit z: Monoid[A]): A = b.valueOrZero(self)(a)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;That's exactly what we need to have the following implementation of a functional &lt;code&gt;computeSalary&lt;/CODE&gt; that uses monoids on Endomorphisms to compose our functions of computing the salary components ..&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;// compose using mappend of endomorphism&lt;br /&gt;def computeSalary(sc: SalaryConfig, basic: Double) = {&lt;br /&gt;  val e = &lt;br /&gt;    sc.surcharge ?? plusSurcharge.endo     |+|&lt;br /&gt;    sc.tax ?? plusTax.endo                 |+|&lt;br /&gt;    sc.bonus ?? plusBonus.endo             |+| &lt;br /&gt;    sc.allowance ?? plusAllowance.endo &lt;br /&gt;  e run basic&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;b&gt;&lt;i&gt;More Generalization - Abstracting over Types ..&lt;/I&gt;&lt;/B&gt;&lt;br /&gt;&lt;br /&gt;We can generalize the solution further and abstract upon the type that represents the collection of component functions. In the above implementation we are picking each function individually and doing an &lt;code&gt;append&lt;/CODE&gt; on the monoid. Instead we can abstract over a type constructor that allows us to fold the append operation over a collection of elements.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;Foldable[]&lt;/CODE&gt; is an abstraction which allows its elements to be folded over. Scalaz defines instances of &lt;code&gt;Foldable[]&lt;/CODE&gt; typeclass for &lt;code&gt;List&lt;/CODE&gt;, &lt;code&gt;Vector&lt;/CODE&gt; etc. so we don't care about the underlying type as long as it has an instance of &lt;code&gt;Foldable[]&lt;/CODE&gt;. And &lt;code&gt;Foldable[]&lt;/CODE&gt; has a method &lt;code&gt;foldMap&lt;/CODE&gt; that makes a &lt;code&gt;Monoid&lt;/CODE&gt; out of every element of the &lt;code&gt;Foldable[]&lt;/CODE&gt; using a supplied function and then folds over the structure using the &lt;code&gt;append&lt;/CODE&gt; function of the &lt;code&gt;Monoid&lt;/CODE&gt;.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;trait Foldable[F[_]]  { self =&gt;&lt;br /&gt;  def foldMap[A,B](fa: F[A])(f: A =&gt; B)(implicit F: Monoid[B]): B&lt;br /&gt;  //..&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;In our example, &lt;code&gt;f: A =&gt; B&lt;/CODE&gt; is the &lt;code&gt;endo&lt;/CODE&gt; function and the &lt;code&gt;append&lt;/CODE&gt; is the &lt;code&gt;append&lt;/CODE&gt; of &lt;code&gt;Endo&lt;/CODE&gt; which composes all the functions that form the &lt;code&gt;Foldable[]&lt;/CODE&gt; structure. Here's the version using &lt;code&gt;foldMap&lt;/CODE&gt; ..&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;def computeSalary(sc: SalaryConfig, basic: Double) = {&lt;br /&gt;  val components = &lt;br /&gt;    List((sc.surcharge, plusSurcharge), &lt;br /&gt;         (sc.tax, plusTax), &lt;br /&gt;         (sc.bonus, plusBonus),&lt;br /&gt;         (sc.allowance, plusAllowance)&lt;br /&gt;    )&lt;br /&gt;  val e = components.foldMap(e =&gt; e._1 ?? e._2.endo)&lt;br /&gt;  e run basic&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This is an exercise which discusses how to apply transformations on values when you need to model endomorphisms. Instead of thinking in terms of generic composition of functions, we exploited the types more, discovered that our tranformations are actually endomorphisms. And then applied the properties of endomorphism to model function composition as monoidal appends. The moment we modeled at a higher level of abstraction (endomorphism rather than native functions), we could use the zero element of the monoid as the composable null object in the sequence of function transformations. &lt;br /&gt;&lt;br /&gt;In case you are interested I have the whole &lt;a HREF="https://github.com/debasishg/scala-snippets/blob/master/src/main/scala/monoids.scala"&gt;working example&lt;/A&gt; in my github repo.&lt;br /&gt;</content><link rel="replies" type="application/atom+xml" href="http://debasishg.blogspot.com/feeds/8500761222734440572/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=22587889&amp;postID=8500761222734440572" title="8 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/22587889/posts/default/8500761222734440572" /><link rel="self" type="application/atom+xml" href="http://debasishg.blogspot.com/feeds/posts/default/8500761222734440572" /><link rel="alternate" type="text/html" href="http://debasishg.blogspot.com/2013/03/an-exercise-in-refactoring-playing.html" title="An exercise in Refactoring - Playing around with Monoids and Endomorphisms" /><author><name>Debasish Ghosh</name><uri>https://plus.google.com/106871002817915335660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh4.googleusercontent.com/-JUSCd5diPuU/AAAAAAAAAAI/AAAAAAAABuo/RF-pdPiR7gE/s512-c/photo.jpg" /></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-22587889.post-5099860375622051800</id><published>2013-02-15T17:35:00.000+05:30</published><updated>2013-02-15T17:35:15.330+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="dsl" /><category scheme="http://www.blogger.com/atom/ns#" term="scala" /><title type="text">A DSL with an Endo - monoids for free</title><content type="html">When we design a domain model, one of the issues that we care about is abstraction of implementation from the user level API. Besides making the published contract simple, this also decouples the implementation and allows post facto optimization to be done without any impact on the user level API.&lt;br /&gt;&lt;br /&gt;Consider a class like the following ..&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;// a sample task in a project&lt;br /&gt;case class Task(name: String) &lt;br /&gt;&lt;br /&gt;// a project with a list of tasks &amp; dependencies amongst the&lt;br /&gt;// various tasks&lt;br /&gt;case class Project(name: String, &lt;br /&gt;                   startDate: java.util.Date, &lt;br /&gt;                   endDate: Option[java.util.Date] = None, &lt;br /&gt;                   tasks: List[Task] = List(), &lt;br /&gt;                   deps: List[(Task, Task)] = List())&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;We can always use the algebraic data type definition above to add tasks and dependencies to a project. Besides being cumbersome as a user level API, it also is a way to program too close to the implementation. The user is coupled to the fact that we use a &lt;code&gt;List&lt;/code&gt; to store tasks, making it difficult to use any alternate implementation in the future. We can offer a Builder like OO interface with fluent APIs, but that also adds to the verbosity of implementation, makes builders mutable and is generally more difficult to compose with other generic functional abstractions. &lt;br /&gt;&lt;br /&gt;Ideally we should be having a DSL that lets users create projects and add tasks and dependencies to them.&lt;br /&gt;&lt;br /&gt;In this post I will discuss a few functional abstractions that will stay behind from the user APIs, and yet provide the compositional power to wire up the DSL. This is a post inspired by this &lt;a HREF="http://ocharles.org.uk/blog/posts/2013-02-12-quick-dsls-with-endo-writers.html"&gt;post&lt;/A&gt; which discusses a similar DSL design using Endo and Writers in Haskell.&lt;br /&gt;&lt;br /&gt;Let's address the issues one by one. We need to &lt;i&gt;accumulate&lt;/I&gt; tasks that belong to the project. So we need an abstraction that helps in this &lt;i&gt;accumulation&lt;/I&gt; e.g. concatenation in a list, or in a set or in a Map .. etc. One abstraction that comes to mind is a &lt;code&gt;Monoid&lt;/CODE&gt; that gives us an associative binary operation between two objects of a type that form a monoid. &lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;trait Monoid[T] {&lt;br /&gt;  def append(m1: T, m2: T): T&lt;br /&gt;  def zero: T&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;A &lt;code&gt;List&lt;/CODE&gt; is a monoid with concatenation as the &lt;code&gt;append&lt;/code&gt;. But since we don't want to expose the concrete data structure to the client API, we can talk in terms of monoids.&lt;br /&gt;&lt;br /&gt;The other data structure that we need is some form of an abstraction that will offer us the writing operation into the monoid. A &lt;code&gt;Writer&lt;/CODE&gt; monad is an example of this. In fact the combination of a &lt;code&gt;Writer&lt;/CODE&gt; and a &lt;code&gt;Monoid&lt;/CODE&gt; is potent enough to have such a DSL in the making. Tony Morris used this combo to implement a &lt;a HREF="https://github.com/tonymorris/writer-monad/blob/master/src/docbook/WriterDemo.scala"&gt;logging functionality&lt;/A&gt; ..&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;for {&lt;br /&gt;  a &lt;- k withvaluelog ("starting with " + _)&lt;br /&gt;  b &lt;- (a + 7) withlog "adding 7"&lt;br /&gt;  c &lt;- (b * 3).nolog&lt;br /&gt;  d &lt;- c.toString.reverse.toInt withvaluelog ("switcheroo with " + _)&lt;br /&gt;  e &lt;- (d % 2 == 0) withlog "is even?"&lt;br /&gt;} yield e&lt;br /&gt;&lt;/pre&gt;We could use this same technique here. But we have a problem - &lt;code&gt;Project&lt;/CODE&gt; is not a monoid and we don't have a definition of &lt;code&gt;zero&lt;/CODE&gt; for a &lt;code&gt;Project&lt;/CODE&gt; that we can use to make it a &lt;code&gt;Monoid&lt;/CODE&gt;.  Is there something that would help us get a monoid from &lt;code&gt;Project&lt;/CODE&gt; i.e. allow us to use &lt;code&gt;Project&lt;/CODE&gt; in a monoid ? &lt;br&gt;&lt;br&gt;Enter &lt;code&gt;Endo&lt;/CODE&gt; .. an endomorphism which is simply a function that takes an argument of type &lt;code&gt;T&lt;/CODE&gt; and returns the same type. In Scala, we can state this as ..  &lt;pre class="brush: scala"&gt;sealed trait Endo[A] {&lt;br /&gt;  // The captured function&lt;br /&gt;  def run: A =&gt; A&lt;br /&gt;  //..&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;a HREF="https://github.com/scalaz/scalaz"&gt;Scalaz&lt;/A&gt; defines &lt;code&gt;Endo[A]&lt;/CODE&gt; and provides a lot of helper functions and syntactic sugars to use endomorphisms. Among its other properties, &lt;code&gt;Endo[A]&lt;/CODE&gt; provides a natural monoid and allows us to use &lt;code&gt;A&lt;/CODE&gt; in a &lt;code&gt;Monoid&lt;/CODE&gt;. In other words, endomorphisms of &lt;code&gt;A&lt;/CODE&gt; form a monoid under composition. In our case we can define an &lt;code&gt;Endo[Project]&lt;/CODE&gt; as a function that takes a &lt;code&gt;Project&lt;/CODE&gt; and returns a &lt;code&gt;Project&lt;/CODE&gt;. We can then use it with a &lt;code&gt;Writer&lt;/CODE&gt; (as above) and implement the accumulation of tasks within a &lt;code&gt;Project&lt;/CODE&gt;. &lt;br&gt;&lt;br&gt;&lt;i&gt;Exercise: Implement Tony Morris' logger without side-effects using an Endo.&lt;/i&gt;&lt;br&gt;&lt;br&gt;Here's how we would like to accumulate tasks in our DSL ..  &lt;pre class="brush: scala"&gt;for {&lt;br /&gt;  _ &lt;- task("Study Customer Requirements")&lt;br /&gt;  _ &lt;- task("Analyze Use Cases")&lt;br /&gt;  a &lt;- task("Develop code")&lt;br /&gt;} yield a&lt;br /&gt;&lt;/pre&gt;&lt;br&gt;&lt;br&gt;Let's define a function that adds a &lt;code&gt;Task&lt;/CODE&gt; to a &lt;code&gt;Project&lt;/CODE&gt; ..  &lt;pre class="brush: scala"&gt;// add task to a project&lt;br /&gt;val withTask = (t: Task, p: Project) =&gt; p.copy(tasks = t :: p.tasks)&lt;br /&gt;&lt;/pre&gt;&lt;br&gt;&lt;br&gt;and use this function to define the DSL API &lt;code&gt;task&lt;/CODE&gt; which makes an &lt;code&gt;Endo[Project]&lt;/CODE&gt; and passes it as a &lt;code&gt;Monoid&lt;/CODE&gt; to the &lt;code&gt;Writer&lt;/CODE&gt; monad. In the following snippet, &lt;code&gt;(p: Project) =&gt; withTask(t, p)&lt;/CODE&gt; is a mapping from &lt;code&gt;Project =&gt; Project&lt;/CODE&gt;, which gets converted to an &lt;code&gt;Endo&lt;/CODE&gt; and then passed to the &lt;code&gt;Writer&lt;/CODE&gt; monad for adding to the task list of the &lt;code&gt;Project&lt;/CODE&gt;.  &lt;pre class="brush: scala"&gt;def task(n: String): Writer[Endo[Project], Task] = {&lt;br /&gt;  val t = Task(n)&lt;br /&gt;  for {&lt;br /&gt;    _ &lt;- tell(((p: Project) =&gt; withTask(t, p)).endo)&lt;br /&gt;  } yield t&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br&gt;The DSL snippet above is a monad comprehension. Let's add some more syntax to the DSL by defining dependencies of a Project. That's also a mapping from one &lt;code&gt;Project&lt;/CODE&gt; state to another and can be realized using a similar function like &lt;code&gt;withTask&lt;/CODE&gt; ..  &lt;pre class="brush: scala"&gt;// add project dependency&lt;br /&gt;val withDependency = (t: Task, on: Task, p: Project) =&gt; &lt;br /&gt;  p.copy(deps = (t, on) :: p.deps)&lt;br /&gt;&lt;/pre&gt;&lt;br&gt;.. and define a function &lt;code&gt;dependsOn&lt;/CODE&gt; to our DSL that allows the user to add the explicit dependencies amongst tasks. But this time instead of making it a standalone function we will make it a method of the class &lt;code&gt;Task&lt;/CODE&gt;. This is only for getting some free syntactic sugar in the DSL. Here's the modified &lt;code&gt;Task&lt;/code&gt; ADT ..  &lt;pre class="brush: scala"&gt;case class Task(name: String) {&lt;br /&gt;  def dependsOn(on: Task): Writer[Endo[Project], Task] = {&lt;br /&gt;    for {&lt;br /&gt;      _ &lt;- tell(((p: Project) =&gt; withDependency(this, on, p)).endo)&lt;br /&gt;    } yield this&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Finally we define the last API of our DSL that glues together the building of the Project and the addition of tasks and dependencies without directly coupling the user to some of the underlying implementation artifacts.  &lt;pre class="brush: scala"&gt;def project(name: String, startDate: Date)(e: Writer[Endo[Project], Task]) = {&lt;br /&gt;  val p = Project(name, startDate)&lt;br /&gt;  e.run._1(p)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;And we can finally create a &lt;code&gt;Project&lt;/CODE&gt; along with tasks and dependencies using our DSL ..  &lt;pre class="brush: scala"&gt;project("xenos", now) {&lt;br /&gt;  for {&lt;br /&gt;    a &lt;- task("study customer requirements")&lt;br /&gt;    b &lt;- task("analyze usecases")&lt;br /&gt;    _ &lt;- b dependsOn a&lt;br /&gt;    c &lt;- task("design &amp; code")&lt;br /&gt;    _ &lt;- c dependsOn b&lt;br /&gt;    d &lt;- c dependsOn a&lt;br /&gt;  } yield d&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;In case you are interested I have the whole &lt;a HREF="https://github.com/debasishg/scala-snippets/blob/master/src/main/scala/endodsl.scala"&gt;working example&lt;/A&gt; in my github repo.</content><link rel="replies" type="application/atom+xml" href="http://debasishg.blogspot.com/feeds/5099860375622051800/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=22587889&amp;postID=5099860375622051800" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/22587889/posts/default/5099860375622051800" /><link rel="self" type="application/atom+xml" href="http://debasishg.blogspot.com/feeds/posts/default/5099860375622051800" /><link rel="alternate" type="text/html" href="http://debasishg.blogspot.com/2013/02/a-dsl-with-endo-monoids-for-free.html" title="A DSL with an Endo - monoids for free" /><author><name>Debasish Ghosh</name><uri>https://plus.google.com/106871002817915335660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh4.googleusercontent.com/-JUSCd5diPuU/AAAAAAAAAAI/AAAAAAAABuo/RF-pdPiR7gE/s512-c/photo.jpg" /></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-22587889.post-4489064465464541598</id><published>2013-02-01T12:27:00.000+05:30</published><updated>2013-02-01T16:28:23.592+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="patterns" /><category scheme="http://www.blogger.com/atom/ns#" term="DI" /><category scheme="http://www.blogger.com/atom/ns#" term="scala" /><title type="text">Modular Abstractions in Scala with Cakes and Path Dependent Types</title><content type="html">I have been trying out various options of implementing the &lt;a HREF="http://lampwww.epfl.ch/~odersky/papers/ScalableComponent.html"&gt;Cake pattern&lt;/A&gt; in Scala, considered to be one of the many ways of doing dependency injection without using any additional framework. There are other (more functional) ways of doing the same thing, one of which I &lt;a HREF="http://debasishg.blogspot.in/2010/02/dependency-injection-as-function.html"&gt;blogged&lt;/A&gt; about before and also &lt;a HREF="http://vimeo.com/23547652"&gt;talked&lt;/A&gt; about in a NY Scala meetup. But I digress ..&lt;br /&gt;&lt;br /&gt;Call it DI or not, the Cake pattern is one of the helpful techniques to implement modular abstractions in Scala. You weave your abstract components (aka traits), layering on the dependencies and commit to implementations only at the end of the world. I was trying to come up with an implementation that does not use self type annotations. It's not that I think self type annotations are kludgy or anything but I don't find them used elsewhere much besides the Cake pattern. And of course mutually recursive self annotations are a code smell that makes your system anti-modular.&lt;br /&gt;&lt;br /&gt;In the following implementation I use path dependent types, which have become a regular feature in Scala 2.10. Incidentally it was there since long back under the blessings of an experimental feature, but has come out in public only in 2.10. The consequence is that instead of self type annotations or inheritance I will be configuring my dependencies using composition.&lt;br /&gt;&lt;br /&gt;Let me start with some basic abstractions of a very simple domain model. The core component that I will build is a service that reports the portfolio of clients as a balance. The example has been simplified for illustration purposes - the actual real life model has a much more complex implementation.&lt;br /&gt;&lt;br /&gt;A &lt;i&gt;Portfolio&lt;/I&gt; is a collection of &lt;i&gt;Balances&lt;/I&gt;. A &lt;i&gt;Balance&lt;/I&gt; is a position of an &lt;i&gt;Account&lt;/I&gt; in a specific &lt;i&gt;Currency&lt;/I&gt; as on a particular &lt;i&gt;Date&lt;/I&gt;. Expressing this in simple terms, we have the following traits ..&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;// currency&lt;br /&gt;sealed trait Currency&lt;br /&gt;case object USD extends Currency&lt;br /&gt;case object EUR extends Currency&lt;br /&gt;case object AUD extends Currency&lt;br /&gt;&lt;br /&gt;//account&lt;br /&gt;case class Account(no: String, name: String, openedOn: Date, status: String)&lt;br /&gt;&lt;br /&gt;trait BalanceComponent {&lt;br /&gt;  type Balance&lt;br /&gt;&lt;br /&gt;  def balance(amount: Double, currency: Currency, asOf: Date): Balance&lt;br /&gt;  def inBaseCurrency(b: Balance): Balance&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The interesting point to note is that the actual type of &lt;code&gt;Balance&lt;/CODE&gt; has been abstracted in &lt;code&gt;BalanceComponent&lt;/CODE&gt;, since various services may choose to use various representations of a Balance. And this is one of the layers of the Cake that we will mix finally ..&lt;br /&gt;&lt;br /&gt;Just a note for the uninitiated, a base currency is typically considered the domestic currency or accounting currency. For accounting purposes, a firm may use the base currency to represent all profits and losses. So we may have some service or component that would like to have the balances reported in base currency.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;trait Portfolio {&lt;br /&gt;  val bal: BalanceComponent&lt;br /&gt;  import bal._&lt;br /&gt;&lt;br /&gt;  def currentPortfolio(account: Account): List[Balance]&lt;br /&gt;} &lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Portfolio uses the abstract &lt;code&gt;BalanceComponent&lt;/CODE&gt; and does not commit to any specific implementation. And the &lt;code&gt;Balance&lt;/CODE&gt; in the return type of the method &lt;code&gt;currentPortfolio&lt;/CODE&gt; is actually a path dependent type, made to look nice through the object import syntax.&lt;br /&gt;&lt;br /&gt;Now let's have some standalone implementations of the above components .. we are still not there yet to mix the cake ..&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;// report balance as a TUPLE3 - simple&lt;br /&gt;trait SimpleBalanceComponent extends BalanceComponent {&lt;br /&gt;  type Balance = (Double, Currency, Date)&lt;br /&gt;&lt;br /&gt;  override def balance(amount: Double, currency: Currency, asOf: Date) = &lt;br /&gt;    (amount, currency, asOf)&lt;br /&gt;  override def inBaseCurrency(b: Balance) = &lt;br /&gt;    ((b._1) * baseCurrencyFactor.get(b._2).get, baseCurrency, b._3)&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// report balance as an ADT&lt;br /&gt;trait CustomBalanceComponent extends BalanceComponent {&lt;br /&gt;  type Balance = BalanceRep&lt;br /&gt;&lt;br /&gt;  // balance representation&lt;br /&gt;  case class BalanceRep(amount: Double, currency: Currency, asOf: Date)&lt;br /&gt;&lt;br /&gt;  override def balance(amount: Double, currency: Currency, asOf: Date) = &lt;br /&gt;    BalanceRep(amount, currency, asOf)&lt;br /&gt;  override def inBaseCurrency(b: Balance) = &lt;br /&gt;    BalanceRep((b.amount) * baseCurrencyFactor.get(b.currency).get, baseCurrency, b.asOf)&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;And a sample implementation of &lt;code&gt;ClientPortfolio&lt;/CODE&gt; that adds logic without yet commiting to any concrete type for the &lt;code&gt;BalanceComponent&lt;/CODE&gt;.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;trait ClientPortfolio extends Portfolio {&lt;br /&gt;  val bal: BalanceComponent&lt;br /&gt;  import bal._&lt;br /&gt;&lt;br /&gt;  override def currentPortfolio(account: Account) = {&lt;br /&gt;    //.. actual impl will fetch from database&lt;br /&gt;    List(&lt;br /&gt;      balance(1000, EUR, Calendar.getInstance.getTime),&lt;br /&gt;      balance(1500, AUD, Calendar.getInstance.getTime)&lt;br /&gt;    )&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Similar to &lt;code&gt;ClientPortfolio&lt;/CODE&gt;, we can have multiple implementations of Portfolio reporting that reports balances in various forms. So our cake has started taking shape. We have the &lt;code&gt;Portfolio&lt;/CODE&gt; component and the BalanceComponent already weaved in without any implementation. Let's add yet another layer to the mix, maybe for fun - a decorator for the &lt;code&gt;Portfolio&lt;/CODE&gt;.&lt;br /&gt;&lt;br /&gt;We add &lt;code&gt;Auditing&lt;/CODE&gt; as a component which can decorate *any* &lt;code&gt;Portfolio&lt;/CODE&gt; component and report the balance of an account in base currency. Note that &lt;code&gt;Auditing&lt;/CODE&gt; needs to abstract implementations of &lt;code&gt;BalanceComponent&lt;/CODE&gt; as well as &lt;code&gt;Portfolio&lt;/CODE&gt; since the idea is to decorate any &lt;code&gt;Portfolio&lt;/CODE&gt; component using any of the underlying &lt;code&gt;BalanceComponent&lt;/CODE&gt; implementations.&lt;br /&gt;&lt;br /&gt;Many cake implementations use self type annotations (or inheritance) for this. I will be using composition and path dependent types.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;trait Auditing extends Portfolio {&lt;br /&gt;  val semantics: Portfolio&lt;br /&gt;  val bal: semantics.bal.type&lt;br /&gt;  import bal._&lt;br /&gt;&lt;br /&gt;  override def currentPortfolio(account: Account) = {&lt;br /&gt;    semantics.currentPortfolio(account) map inBaseCurrency&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Note how the &lt;code&gt;Auditing&lt;/CODE&gt; component uses the same &lt;code&gt;Balance&lt;/CODE&gt; implementation as the underlying decorated &lt;code&gt;Portfolio&lt;/CODE&gt; component, enforced through path dependent types.&lt;br /&gt;&lt;br /&gt;And we have reached the end of the world without yet committing to any implementation of our components .. But now let's do that and get a concrete service instantiated ..&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;object SimpleBalanceComponent extends SimpleBalanceComponent&lt;br /&gt;object CustomBalanceComponent extends CustomBalanceComponent&lt;br /&gt;&lt;br /&gt;object ClientPortfolioAuditService1 extends Auditing {&lt;br /&gt;  val semantics = new ClientPortfolio { val bal = SimpleBalanceComponent }&lt;br /&gt;  val bal: semantics.bal.type = semantics.bal&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;object ClientPortfolioAuditService2 extends Auditing {&lt;br /&gt;  val semantics = new ClientPortfolio { val bal = CustomBalanceComponent }&lt;br /&gt;  val bal: semantics.bal.type = semantics.bal&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Try out in your Repl and see how the two services behave the same way abstracting away all implementations of components from the user ..&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: scala"&gt;scala&gt; ClientPortfolioAuditService1.currentPortfolio(Account("100", "dg", java.util.Calendar.getInstance.getTime, "a"))&lt;br /&gt;res0: List[(Double, com.redis.cake.Currency, java.util.Date)] = List((1300.0,USD,Thu Jan 31 12:58:35 IST 2013), (1800.0,USD,Thu Jan 31 12:58:35 IST 2013))&lt;br /&gt;&lt;br /&gt;scala&gt; ClientPortfolioAuditService2.currentPortfolio(Account("100", "dg", java.util.Calendar.getInstance.getTime, "a"))&lt;br /&gt;res1: List[com.redis.cake.ClientPortfolioAuditService2.bal.Balance] = List(BalanceRep(1300.0,USD,Thu Jan 31 12:58:46 IST 2013), BalanceRep(1800.0,USD,Thu Jan 31 12:58:46 IST 2013))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The technique discussed above is inspired from the paper &lt;a HREF="http://www.mathematik.uni-marburg.de/~rendel/hofer08polymorphic.pdf"&gt;Polymoprhic Embedding of DSLs&lt;/A&gt;. I have been using this technique for quite some time and I have discussed a somewhat similar implementation in my book &lt;a HREF="http://manning.com/ghosh"&gt;DSLs In Action&lt;/A&gt; while discussing internal DSL design in Scala.&lt;br /&gt;&lt;br /&gt;And in case you are interested in  the full code, I have uploaded it on my &lt;a HREF="https://github.com/debasishg/scala-snippets/blob/master/src/main/scala/cake.scala"&gt;Github&lt;/A&gt;.</content><link rel="replies" type="application/atom+xml" href="http://debasishg.blogspot.com/feeds/4489064465464541598/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=22587889&amp;postID=4489064465464541598" title="20 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/22587889/posts/default/4489064465464541598" /><link rel="self" type="application/atom+xml" href="http://debasishg.blogspot.com/feeds/posts/default/4489064465464541598" /><link rel="alternate" type="text/html" href="http://debasishg.blogspot.com/2013/02/modular-abstractions-in-scala-with.html" title="Modular Abstractions in Scala with Cakes and Path Dependent Types" /><author><name>Debasish Ghosh</name><uri>https://plus.google.com/106871002817915335660</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh4.googleusercontent.com/-JUSCd5diPuU/AAAAAAAAAAI/AAAAAAAABuo/RF-pdPiR7gE/s512-c/photo.jpg" /></author><thr:total>20</thr:total></entry></feed>
