<?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-06-17T01:13:47.020+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>301</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-2712980585988306755</id><published>2013-06-03T12:10:00.000+05:30</published><updated>2013-06-03T12:10:47.564+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="functional" /><category scheme="http://www.blogger.com/atom/ns#" term="scalaz" /><category scheme="http://www.blogger.com/atom/ns#" term="dsl" /><category scheme="http://www.blogger.com/atom/ns#" term="scala" /><title type="text">Endo is the new fluent API</title><content type="html">I tweeted this over the weekend ..  &lt;blockquote class="twitter-tweet"&gt;&lt;p&gt;a good title for a possible blog post .. endo is the new fluent API ..&lt;/p&gt;&amp;mdash; Debasish Ghosh (@debasishg) &lt;a href="https://twitter.com/debasishg/status/340885372735193089"&gt;June 1, 2013&lt;/a&gt;&lt;/blockquote&gt;&lt;script async src="//platform.twitter.com/widgets.js" charset="utf-8"&gt;&lt;/script&gt;   My last two blog posts have been about endomorphisms and how it combines with the other functional structures to help you write expressive and composable code. In &lt;a HREF="http://debasishg.blogspot.in/2013/02/a-dsl-with-endo-monoids-for-free.html"&gt;A DSL with an Endo - monoids for free&lt;/A&gt;, endos play with Writer monad and implement a DSL for a sequence of activities through monoidal composition. And in &lt;a HREF="http://debasishg.blogspot.in/2013/03/an-exercise-in-refactoring-playing.html"&gt;An exercise in Refactoring - Playing around with Monoids and Endomorphisms&lt;/A&gt;, I discuss a refactoring exercise that exploits the monoid of an endo to make composition easier.   Endomorphisms help you lift your computation into a data type that gives you an instance of a monoid. And the &lt;code&gt;mappend&lt;/code&gt; operation of the monoid is the function composition. Hence once you have the &lt;code&gt;Endo&lt;/code&gt; for your type defined, you get a nice declarative syntax for the operations that you want to compose, resulting in a fluent API.  Just a quick recap .. endomorphisms are functions that map a type on to itself and offer composition over monoids. Given an endomorphism we can define an implicit monoid instance ..  &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; I am not going into the details of this, which I discussed at length in my earlier posts. In this article I will sum up with yet another use case for making fluent APIs using the monoid instance of an Endo. Consider an example from the domain of securities trading, where a security trade goes through a sequence of transformations in its lifecycle through the trading process ..  Here's a typical &lt;code&gt;Trade&lt;/CODE&gt; model (very very trivialified for demonstration) ..  &lt;pre class="brush: scala"&gt;sealed trait Instrument&lt;br /&gt;case class Security(isin: String, name: String) extends Instrument&lt;br /&gt;&lt;br /&gt;case class Trade(refNo: String, tradeDate: Date, valueDate: Option[Date] = None, &lt;br /&gt;  ins: Instrument, principal: BigDecimal, net: Option[BigDecimal] = None, &lt;br /&gt;  status: TradeStatus = CREATED)&lt;br /&gt;&lt;/pre&gt; Modeling a typical lifecycle of a trade is complex. But for illustration, let's consider these simple ones which need to executed on a trade in sequence .. &lt;ol&gt;&lt;li&gt;Validate the trade&lt;/LI&gt;&lt;li&gt;Assign value date to the trade, which will ideally be the settlement date&lt;/LI&gt;&lt;li&gt;Enrich the trade with tax/fees and net trade value&lt;/LI&gt;&lt;li&gt;Journalize the trade in books &lt;/OL&gt;Each of the functions take a &lt;code&gt;Trade&lt;/CODE&gt; and return a copy of the &lt;code&gt;Trade&lt;/CODE&gt; with some attributes modified. A naive way of doing that will be as follows ..&lt;/LI&gt; &lt;pre class="brush: scala"&gt;def validate(t: Trade): Trade = //..&lt;br /&gt;&lt;br /&gt;def addValueDate(t: Trade): Trade = //..&lt;br /&gt;&lt;br /&gt;def enrich(t: Trade): Trade = //..&lt;br /&gt;&lt;br /&gt;def journalize(t: Trade): Trade = //..&lt;br /&gt;&lt;/pre&gt;and invoke these methods in sequence while modeling the lifecycle. Instead we try to make it more composable and lift the function &lt;code&gt;Trade =&gt; Trade&lt;/CODE&gt; within the &lt;code&gt;Endo&lt;/CODE&gt; ..  &lt;pre class="brush: scala"&gt;type TradeLifecycle = Endo[Trade]&lt;br /&gt;&lt;/pre&gt;and here's the implementation ..  &lt;pre class="brush: scala"&gt;// validate the trade: business logic elided&lt;br /&gt;def validate: TradeLifecycle = &lt;br /&gt;  ((t: Trade) =&gt; t.copy(status = VALIDATED)).endo&lt;br /&gt;&lt;br /&gt;// add value date to the trade (for settlement)&lt;br /&gt;def addValueDate: TradeLifecycle = &lt;br /&gt;  ((t: Trade) =&gt; t.copy(valueDate = Some(t.tradeDate), status = VALUE_DATE_ADDED)).endo&lt;br /&gt;&lt;br /&gt;// enrich the trade: add taxes and compute net value: business logic elided&lt;br /&gt;def enrich: TradeLifecycle = &lt;br /&gt;  ((t: Trade) =&gt; t.copy(net = Some(t.principal + 100), status = ENRICHED)).endo&lt;br /&gt;&lt;br /&gt;// journalize the trade into book: business logic elided&lt;br /&gt;def journalize: TradeLifecycle = &lt;br /&gt;  ((t: Trade) =&gt; t.copy(status = FINALIZED)).endo&lt;br /&gt;&lt;/pre&gt;Now endo has an instance of &lt;code&gt;Monoid&lt;/CODE&gt; defined by scalaz and the &lt;code&gt;mappend&lt;/CODE&gt; of &lt;code&gt;Endo&lt;/CODE&gt; is function composition .. Hence here's our lifecycle model using the holy monoid of endo ..  &lt;pre class="brush: scala"&gt;def doTrade(t: Trade) =&lt;br /&gt;  (journalize |+| enrich |+| addValueDate |+| validate).apply(t)&lt;br /&gt;&lt;/pre&gt;It's almost the specification that we listed above in numbered bullets. Note the inside out sequence that's required for the composition to take place in proper order.      &lt;br/&gt;&lt;br/&gt;&lt;h3&gt;Why not plain old composition ?&lt;/H3&gt;&lt;br/&gt;A valid question. The reason - abstraction. Abstracting the composition within types helps you compose the result with other types, as we saw in my earlier blog posts. In one of them we built larger abstractions using the Writer monad with &lt;code&gt;Endo&lt;/code&gt; and in the other we used the &lt;code&gt;mzero&lt;/code&gt; of the monoid as a fallback during composition thereby avoiding any special case branch statements.    &lt;br/&gt;&lt;br/&gt;&lt;h3&gt;One size doesn't fit all .. &lt;/H3&gt;&lt;br/&gt;The endo and its monoid compose beautifully and gives us a domain friendly syntax that expresses the business functionality ina  nice succinct way. But it's not a pattern which you can apply everywhere where you need to compose a bunch of domain behaviors. Like every idiom, it has its shortcomings and you need different sets of solutions in your repertoire. For example the above solution doesn't handle any of the domain exceptions - what if the validation fails ? With the above strategy the only way you can handle this situation is to throw exceptions from validate function. But exceptions are side-effects and in functional programming there are more cleaner ways to tame the evil. And for that you need different patterns in practice. More on that in subsequent posts ..</content><link rel="replies" type="application/atom+xml" href="http://debasishg.blogspot.com/feeds/2712980585988306755/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=22587889&amp;postID=2712980585988306755" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/22587889/posts/default/2712980585988306755" /><link rel="self" type="application/atom+xml" href="http://debasishg.blogspot.com/feeds/posts/default/2712980585988306755" /><link rel="alternate" type="text/html" href="http://debasishg.blogspot.com/2013/06/endo-is-new-fluent-api.html" title="Endo is the new fluent API" /><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>1</thr:total></entry><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="10 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>10</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></feed>
