tag:blogger.com,1999:blog-91887852698135204842019-08-05T03:56:02.067-07:00Side Effect Free RantsTejas Dinkar's space to ramble onlinegjahttp://www.blogger.com/profile/03096275805966250387noreply@blogger.comBlogger4125tag:blogger.com,1999:blog-9188785269813520484.post-59311437896909928522014-01-23T19:30:00.000-08:002014-01-24T08:17:09.442-08:00Functional Programming 101 - With Haskell<p>In this blog post, I&#39;ll attempt to explain some basic concepts of Functional Programming, using Haskell. This blog post isn&#39;t about Haskell per-se, but about one way of approaching this problem, which demonstrates the benefits of functional programming.</p> <p>You can run most of these examples in ghci, by saving the contents of the example into a .hs file, loading up ghci and running :load file.hs.</p> <p>Many thanks to <a href="http://www.iit.edu/csl/cs/faculty/beckman_mattox.shtml">Mattox Beckman</a> for coming up with the programming exercise, and Junjie Ying for coming finding a better data structure for this explanation than I came up with.</p><h2 id='the-problem'>The Problem</h2><p>You are Hercules, about to fight the dreaded Hydra. The Hydra has 9 heads. When a head is chopped off, it spawns 8 more heads. When one of these 8 heads is cut off, each one spawns out 7 more heads. Chopping one of these spawns 6 more heads, and so on until the weakest head of the hydra will not spawn out any more heads.</p> <p>Our job is to figure out how many chops Hercules needs to make in order to kill all heads of the Hydra. And no, it&#39;s not n!.</p><h2 id='prelude-simple-overview-of-haskell-syntax'>Prelude: Simple Overview Of Haskell Syntax</h2><p>Before we dive into code, i&#39;ll explain a few constructs which are unique to Haskell, so it&#39;s easy for non Haskellers.</p> <ul><li>List Creation: You can create a list / array using the : operator. This can even be done lazily to get an infinite list. <script src="https://gist.github.com/24df70ad958b0ba87e37.js?file=basics-1.hs"></script><noscript> <pre>let firstArray = 0:1:[2, 3]<br />-- [0, 1, 2, 3]<br />let infiniteOnes = 1:infiniteOnes<br />-- [1, 1, 1, 1, 1, ........................]<br />-- never stops, hit ctrl-C to get your interpreter back</pre></noscript></li><li>Defining Function: Looks just like defining a variable, but it takes parameters. One way they are different from other languages is the ability to do pattern matching to simplify your code. Here, I define a method that sums all the elements of a list. <script src="https://gist.github.com/24df70ad958b0ba87e37.js?file=basics-2.hs"></script><noscript> <pre>sumOfElements [] = 0<br />sumOfElements (x:xs) = x + sumOfElements xs</pre></noscript></li><li>More List Foo: Adding lists can be done with ++. Checking if a list is empty can be done with null. You can use replicate to create a list with the same elements over and over. <script src="https://gist.github.com/24df70ad958b0ba87e37.js?file=basics-3.hs"></script><noscript> <pre>[1] ++ [3] -- [1, 3]<br />null [] -- True<br />null [1] -- False<br />replicate 2 3 -- [3, 3]</pre></noscript></li></ul><h2 id='choosing-a-data-structure'>Choosing a data structure</h2><p>Let&#39;s choose a simple data structure to represent the hydra. We&#39;ll pick an array to represent the heads of the Hydra, using the <code>level</code> of each head as the value. The initial state of the Hydra (with 9 <code>level 9</code> heads) can be represented as follows: <code>[9, 9, 9, 9, 9, 9, 9, 9, 9]</code>.</p><h2 id='chopping-off-a-head'>Chopping off a head</h2><p>The whole point of functional programming is to build small functions and compose them later. We&#39;ll build a few functions, specific to our domain, and a few more general ones to orchestrate.</p> <p>Let&#39;s first build a specific function to chop off the Hydra&#39;s head. We know that chopping off one <code>level 9</code> head should result in 8 <code>level 8</code> heads (and 8 of the original <code>level 9</code> heads). This is represented as <code>[8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9]</code></p> <p>Let&#39;s build the chop function. It takes a single argument, and the current levels of the all live heads. It will return the state of the heads after chopping the first one.</p> <p>The three lines of code below map to these rules:</p> <ul><li>If there are no heads left, just return <code>[]</code></li><li>If we find that there is a level 1 head at the start of our list, just chop it off and return the rest of the array</li><li>If we find that there is a higher level head at the start of our list, spawn n - 1 heads in it&#39;s place</li></ul> <p><script src="https://gist.github.com/24df70ad958b0ba87e37.js?file=chop.hs"></script><noscript> <pre>chop [] = []<br />chop (1:xs) = xs<br />chop (n:xs) = (replicate (n - 1) (n - 1)) ++ xs<br />----------------------------------------------------<br />chop [1]<br />-- []<br />chop [4]<br />-- [3, 3, 3]<br />chop [3, 3, 3]<br />-- [2, 2, 3, 3]<br />chop [9,9,9,9,9,9,9,9,9]<br />-- [8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9]</pre></noscript></p><h2 id='repeatedly-chopping-heads'>Repeatedly chopping heads</h2><p>Our function chop is a pure function as, given some input, it always returns the same output, without any sort of side effects. Side effects is a general term for modifying inputs / IO Operations / DB Calls, and so on.</p> <p>Since chop is pure function, we can safely call it over and over. Let&#39;s build a list where each element is the result of chopping the previous element. <script src="https://gist.github.com/24df70ad958b0ba87e37.js?file=repeatedly-chop1.hs"></script><noscript> <pre>repeatedlyChop heads = heads:repeatedlyChop (chop heads)<br />----------------------------------------------------------<br />repeatedlyChop [3]<br />-- [[3],[2,2],[1,2],[2],[1], [], [], [] ...]<br />-- this is an infinite list</pre></noscript></p> <p>This paradigm is so common, that we have a functional construct that does this: <a href="http://hackage.haskell.org/package/base-4.6.0.1/docs/Prelude.html#v:iterate">iterate</a>. We can replace the above code with the following: <script src="https://gist.github.com/24df70ad958b0ba87e37.js?file=repeatedly-chop2.hs"></script><noscript> <pre>repeatedlyChop heads = iterate chop heads</pre></noscript></p><h2 id='truncate-that-infinite-list'>Truncate that infinite list</h2><p>Great, we now have built a list of all the states the Hydra is in while Hercules is busy chopping away at it. However, this list goes on forever (we never put in a termination condition in the earlier code), so let&#39;s do that now.</p> <p>We can use a simple empty check (null) to test if the hydra is still alive. Let&#39;s keep items as long as the Hydra is alive <script src="https://gist.github.com/24df70ad958b0ba87e37.js?file=takewhilealive.hs"></script><noscript> <pre>takeWhileAlive (x:xs) = if null x then [] else x:(takeWhileAlive xs)</pre></noscript></p> <p>Putting the two together <script src="https://gist.github.com/24df70ad958b0ba87e37.js?file=iteratethroughheads.hs"></script><noscript> <pre>repeatedlyChopTillDead heads = takeWhileAlive (repeatedlyChopTillDead heads)<br />----------------------------------------------------------------------------<br />repeatedlyChopTillDead [4]<br />-- [[4],[3,3,3],[2,2,3,3],[1,2,3,3],[2,3,3],[1,3,3],[3,3],[2,2,3],[1,2,3],[2,3],[1,3],[3],[2,2],[1,2],[2],[1]]</pre></noscript></p> <p>Again, these patterns are so common, that we can replace the entire thing with a single line. <a href="http://hackage.haskell.org/package/base-4.6.0.1/docs/Prelude.html#v:takeWhile">takeWhile</a> keeps things in the list until the first element that doesn&#39;t match. <script src="https://gist.github.com/24df70ad958b0ba87e37.js?file=repeatedly-simple.hs"></script><noscript> <pre>repeatedlyChopTillDead heads = takeWhile (not.null) (iterate chop heads)</pre></noscript></p><h2 id='finishing-up'>Finishing up</h2><p>Now that we have the sequence of chops needed to kill that Hydra, figuring out the number of chops is just a matter of figuring out how long the sequence is. <script src="https://gist.github.com/24df70ad958b0ba87e37.js?file=count-chops.hs"></script><noscript> <pre>countOfChops heads = length (repeatedlyChopTillDead heads)<br />--------------------------------------------------<br />countOfChops [1] -- 1<br />countOfChops [3] -- 5<br />countOfChops [9,9,9,9,9,9,9,9,9] -- 986409 (this takes a while)</pre></noscript></p><h2 id='extending'>Extending</h2><p>Now that we&#39;ve solved the problem, what next? How easy is it to extend this? Let&#39;s add a new requirement: Hercules, though a half god, can only fight at most n Hydra heads at a time. If the number of Hydra heads goes above n, then hercules dies. Let&#39;s make a function <code>willHerculesDie</code> which takes two parameters, n and the Hydra.</p> <p>Turns out, this is pretty simple. We just need to count all the heads that are alive. If the count is more than n at any point, then we return true, and Hercules dies. <script src="https://gist.github.com/24df70ad958b0ba87e37.js?file=herculeswilldie.hs"></script><noscript> <pre>willHerculesDie n heads = any (> n) (map length (repeatedlyChopTillDead heads))<br />----------------------------------------------------------------------------<br />willHerculesDie 37 [9,9,9,9,9,9,9,9,9] -- False<br />willHerculesDie 36 [9,9,9,9,9,9,9,9,9] -- True</pre></noscript></p><h2 id='so-what-next'>So what next?</h2><p>We&#39;ve built a bunch of really composable functions, and we can look at each one independently to tune the system.</p> <p>You can get Haskell set up with the <a href="http://www.haskell.org/platform/">Haskell Platform</a> and play around with the code <a href="https://gist.github.com/gja/24df70ad958b0ba87e37/#file-hydra-hs">here</a>.</p> <p>Some great books you can check out:</p> <ul><li><a href="http://mitpress.mit.edu/sicp/full-text/book/book.html">Structure and Interpretation of Computer Programs</a></li><li><a href="http://learnyouahaskell.com/">Learn you a Haskell for Great Good</a> - Greatest Haskell Tutorial out there</li><li><a href="https://leanpub.com/fp-oo">Functional Programming for the Object-Oriented Programmer</a></li></ul> <p><hr /><b>If you liked this post, you could:</b><br /> <h4 style="text-align: center;"> <a class="twitter-follow-button" data-show-count="false" href="https://twitter.com/tdinkar">Follow @tdinkar</a></h4> <div style="text-align: center;"> <b><a href="http://news.ycombinator.com/item?id=7113259">upvote it</a> on Hacker News</b></div> <div style="text-align: center;"> <b>or just <a href="http://www.blogger.com/comment.g?blogID=9188785269813520484&postID=5931143789690992852">leave a comment</a></b></div> <br/></p>gjahttp://www.blogger.com/profile/03096275805966250387noreply@blogger.com34tag:blogger.com,1999:blog-9188785269813520484.post-91161713075654519432012-06-30T03:41:00.010-07:002012-07-07T00:29:39.704-07:00Eight Simple Rules for Maintainable Javascript<p>All projects start out small. This is true for the javascript part of any web app. In the beginning, it&#39;s always easy to read, and easy to debug.</p> <p>I&#39;ve put together some of my learnings for client side Javascript</p> <h2>1. Do not let your .js file be the entry point to your code</h2> <p>I&#39;ve seen this anti pattern in most of the codebases I&#39;ve inherited.</p> <p><em>The Trap:</em>The javascript that binds to the DOM <script src="https://gist.github.com/3023040.js?file=trap1.js"></script><noscript> <pre>$(&quot;.submit-button&quot;).click(function(){<br /> server.submit();<br />});</pre></noscript></p> <p>This is a trap for multiple reasons:</p> <ol><li>It&#39;s really hard to figure out what happened when you clicked on a button. Did some callback get triggered? Where is the code for this?</li><li>You&#39;ll can easily get a bunch of callbacks that interfere with each other. Another page of mine has another button called submit button. I need to make sure that this JS is not loaded on that page</li><li>It&#39;s not possible to compile all your javascript assets into a single application.js</li></ol> <p><em>Solution:</em>Wrap everything that is binding to an element, and call that from the html <script src="https://gist.github.com/3023040.js?file=solution1.js"></script><noscript> <pre>function bindElementToSubmit(element) {<br /> element.click(function() {<br /> server.submit();<br /> });<br />}</pre></noscript> <script src="https://gist.github.com/3023040.js?file=solution1.html"></script><noscript> <pre>&lt;div class=&quot;submit-button&quot;&gt;Submit&lt;/div&gt;<br />&lt;script type=&quot;text/javascript&quot;&gt;<br /> bindElementToSubmit($(&quot;.submit-button&quot;));<br />&lt;/script&gt;</pre></noscript></p> <p>Binding things in the HTML helps you keep in your head what is going on in a particular page. It also helps you answer things like how an element is bound (was it &quot;.submit-button&quot;, &quot;#page-submit-button&quot;, or &quot;form &gt; .submit-button&quot;), and makes sure that it&#39;s easy to find when searching for code later.</p> <p><em>Caveat:</em>One caveat to look out for is the order of loading of JavaScript files. The above code requires jQuery loaded for $(document).ready() to work. One alternative is to use window.onLoad(), though that waits for the entire DOM and assets to load.</p> <h2>2. Understand how <em>this</em> works in Javascript</h2> <p>Everything is lexically scoped in Javascript. Except for &#39;this&#39;, which is something that is set depending on how a method is called. Some libraries like jQuery even set the value of &#39;this&#39; to mean things like the object on which a callback is called.</p> <p><em>The Trap:</em>Using a this pointer that&#39;s pointing at the wrong object. <script src="https://gist.github.com/3023040.js?file=trap2.js"></script><noscript> <pre>$(&quot;some-div&quot;).click(function() {<br /> this.html(&quot;loading&quot;); // replaces the current div with 'loading'<br /> $.get(&quot;/foobar&quot;, function(result){<br /> this.html(result); // no such function html!!<br /> });<br />});</pre></noscript></p> <p>Granted, this isn&#39;t all that dangerous because it will be obvious that your code is not working.</p> <p><em>The Solution:</em>Have a convention for what the current object is. I prefer self. <script src="https://gist.github.com/3023040.js?file=solution2.js"></script><noscript> <pre>$(&quot;some-div&quot;).click(function() {<br /> var self = this;<br /> self.html(&quot;loading&quot;);<br /> $.get(&quot;/foobar&quot;, function(result){<br /> self.html(result);<br /> });<br />});</pre></noscript></p> <h2>3. Structure your JS code into logical units</h2> <p>Javascript is a prototype based language. There are a lot of cool things you can do with a prototype based language, but very few of them will help you write a good UI. Most people take the lack of &#39;class&#39; keyword in Javascript to mean the lack of Object Orientation.</p> <p><em>The Trap:</em>A bunch of methods floating around in space <script src="https://gist.github.com/3023040.js?file=trap3.js"></script><noscript> <pre>function processResults(results) {<br /> // do Something<br />}<br /><br />function bindElementToSubmit(element) {<br /> element.click(function(){<br /> server.submit(function(result){<br /> processResults(results);<br /> });<br /> });<br />}<br /><br />bindElementToSubmit($(&quot;.submit-button&quot;));</pre></noscript></p> <p>This is a trap because you aren&#39;t able to group logically related methods together. This would be similar to a bunch of static methods on your server side.</p> <p><em>The Solution:</em>Build some sort of object oriented abstraction over your javascript functions. You can either hand roll your own using javascripts prototype functionality, or you can just drop in something like <a href="https://github.com/rauschma/class-js/blob/master/Class.js">class-js</a><script src="https://gist.github.com/3023040.js?file=solution3.js"></script><noscript> <pre>SubmitPage = Class.extend({<br /> processResults: function(results) {<br /> // do Something<br /> },<br /><br /> constructor: function(element) {<br /> var self = this;<br /> element.click(function(){<br /> server.submit(function(result){<br /> self.processResults(results);<br /> });<br /> }); <br /> }<br />});<br /><br />new SubmitPage($(&quot;.submit-button&quot;));</pre></noscript></p> <h2>4. Use client side templates to render content</h2> <p>Again, this can go into another blog post by itself, and I&#39;ll be writing about this soon.</p> <p><em>The Trap:</em>Having your server return HTML output as the response to an AJAX request, and having the client just dump it into the DOM somewhere</p> <p><em>The Solution:</em>Use something like <a href="http://mustache.github.com/">Mustache.js</a> to render your server side template. I&#39;ll be posting more about this soon.</p> <h2>5. Test your javascript</h2> <p>Just because this is javascript, and not the backend code, does not mean that you should ignore your JS. JS faces just as many (if not loads more) regression bugs than your backend code.</p> <p><em>The Trap:</em>A lot of code without any test coverage</p> <p><em>The Solution:</em>Test your code with something like <a href="https://github.com/pivotal/jasmine/">jasmine</a>. Use one of the addons to jasmine like <a href="https://github.com/pivotal/jasmine-jquery">jasmine-jquery</a>, which lets you bootstrap your tests with a sample DOM, and then run your tests against that DOM.</p> <p>Check out the <a href="http://pivotal.github.com/jasmine/">example specs</a></p> <h2>6. MetaProgramming #ftw</h2> <p>Ruby programmers would already be familiar with some sort of metaprogramming, and JS is almost as powerful. The main feature I miss from ruby is the method_missing.</p> <p>You can open up a class and add methods: <script src="https://gist.github.com/3023040.js?file=6monkeypatch.js"></script><noscript> <pre>String.prototype.alert = function() {<br /> alert(this);<br />};<br /><br />&quot;foobar&quot;.alert();</pre></noscript></p> <p>You can use [] like a poor man&#39;s send: <script src="https://gist.github.com/3023040.js?file=6send.js"></script><noscript> <pre>alertFunction = this[&quot;alert&quot;];<br />alertFunction(&quot;blahblahblah&quot;); // Note that alert will no longer get the same value of this</pre></noscript></p> <p>You can also use [] to define dynamic methods: <script src="https://gist.github.com/3023040.js?file=6define.js"></script><noscript> <pre>for(i = 0; i &lt; 5; i++) { <br /> var times = i; // need to save this in our closure<br /> String.prototype[&quot;alert&quot; + i] = function() {<br /> alert(this + times);<br /> }<br />};<br /><br />&quot;foobar&quot;.alert3()</pre></noscript></p> <h2>7. Know your javascript libraries</h2> <p>This could cover multiple blog posts in itself.</p> <p>Know your options for manipulating the DOM, as well as other things you want to do</p> <p>As a primer, check out the following projects:</p> <ul><li><a href="http://knockoutjs.com/">knockout.js</a></li><li><a href="http://emberjs.com/">ember.js</a> (formerly SproutCore)</li><li><a href="http://backbonejs.org/">backbone.js</a></li><li><a href="http://underscorejs.org/">underscore.js</a></li></ul> <h2>8. Use CoffeeScript</h2> <p>CoffeeScript is a neat little language that compiles down to JS, and has support for almost all of these features baked right in. It namespaces things for you, and fixes the this/self problem, and provides a lot of the functionality that underscore would provide.</p> <p>As an additional benefit, it&#39;s much less code to read. And it&#39;s baked right into rails.</p> <p>You can read more on <a href="http://coffeescript.org/">coffeescript.org</a></p> <p><hr /><b>If you liked this post, you could:</b><br /> <h4 style="text-align: center;"> <a class="twitter-follow-button" data-show-count="false" href="https://twitter.com/tdinkar">Follow @tdinkar</a></h4> <div style="text-align: center;"> <b><a href="http://news.ycombinator.com/item?id=4194066">upvote it</a> on Hacker News</b></div> <div style="text-align: center;"> <b>or just <a href="http://www.blogger.com/comment.g?blogID=9188785269813520484&postID=9116171307565451943">leave a comment</a></b></div> <br/></p>gjahttp://www.blogger.com/profile/03096275805966250387noreply@blogger.com18tag:blogger.com,1999:blog-9188785269813520484.post-2537152150176224102012-06-30T00:31:00.000-07:002013-06-27T22:39:20.660-07:00Using bundler with executables<h2>What Is Bundler?</h2><p>Bundler is a ruby gem loading system. It loads up all the relevant gems for your project, and ensures the versions are correct, before your app takes over.</p><h2>How do I ensure that my executables are bundler aware?</h2><p>When doing a bundle install (or just bundle), always add the option --binstubs. This will create binary wrappers in the bin/ folder of your project. <code>bundle --binstubs</code></p><p>Instead of executing commands directly like this: <code>rake</code></p><p>Execute the command command that is in the bin folder. <code>./bin/rake</code></p><h2>Do I check these /bin/* files in?</h2><p>I usually git ignore them, but, according to the documentation, it&#39;s safe to check in.</p><h2>I hate typing ./bin/rake every time!</h2><p>No problem. You can add a relative path like ./bin to your $PATH</p><ul><li>If you are using rbenv, just add ./bin to your path in your ~/.bashrc</li><li>If you are using rvm, add ./bin into every .rvmrc</li></ul>gjahttp://www.blogger.com/profile/03096275805966250387noreply@blogger.com2tag:blogger.com,1999:blog-9188785269813520484.post-8466024580797160212012-06-30T00:22:00.004-07:002012-06-30T11:34:49.153-07:00Proxy Pattern<h2>Problem Statement</h2> <p>I have a method which does something great, and is nice and small. It does everything i want, except some small feature that isn&#39;t core to the class. For example, I want to do some fudging for the input parameters and/or fudging the output parameters. I want to create another class to handle these orthogonal requirements.</p> <h2>TL;DR - Short summary</h2> <p>Wrap the original object in a proxy which looks like the original object to the outside world. Delegate calls to the original object eventually. This is an example of Aspect Oriented Programming.</p> <h2>Code Example</h2> <p>I&#39;m building this example up as a series of requirements</p> <p>Requirement 1: I want to be able to get my bank balance from the bank. <script src="https://gist.github.com/3022255.js?file=bank.rb"></script></p> <p>Requirement 2: I want to be able to log the fact someone has checked their bank balance <script src="https://gist.github.com/3022255.js?file=bank2.rb"></script></p> <p>Requirement 3: I want to tell everyone that their bank balance is double of what it is really. But logging should log the correct value. <script src="https://gist.github.com/3022255.js?file=bank3.rb"></script></p> <p>Requirement 4: I&#39;ve changed my mind. It&#39;s hard for me to have plausible deniability if i log actual bank balances. Fudge that as well <script src="https://gist.github.com/3022255.js?file=bank4.rb"></script></p> <p>Requirement 5: I want to cache the balance. I still expect logging and doubling. <script src="https://gist.github.com/3022255.js?file=bank5.rb"></script></p> <p>A note on the example: Requirement 3 (the doubling filter) should probably go into the first class, it&#39;s core to the business. I just made it a proxy filter to illustrate the point about output fudging.</p> <h2>Conditions for a good proxy</h2> <ul><li>The constructor accepts the item it is proxying.</li><li>The proxy passes requests to the original object in at least one branch of the code</li><li>The proxy honors all methods of the original object with the same signature (in java world, implements the same interface)</li><li>Proxies must be composable (this will follow from the point above): Proxy1.new(Proxy2.new(Proxy3.new(object)))</li><li>That does not mean the order of proxies is immaterial</li></ul> <h2>Practical Uses</h2> <ul><li>A proxy that caches the response from the inner method</li><li>A proxy that runs the inner method in a single database transaction</li><li>A proxy that adds logging before and after the method is called</li><li>A proxy that validates inputs</li></ul> <h2>DynamicProxy</h2> <p>In the examples above, we overrode a single method bank_balance. Now, imaging you want a proxy to overwrite 50 different methods of an object. Enter DynamicProxy for java, and DynamicProxy/SimpleProxy for .NET. These let you override all methods in a particular interface.</p> <p>Of course, ruby doesn&#39;t need that thanks to method_missing! <script src="https://gist.github.com/3022255.js?file=dynamicproxy.rb"></script></p> <h2>Rack filters</h2> <p>Rack provides an easy way to add proxy pattern to the app called via filters (rails cleans this up as around filters). A filter which does nothing will be as follows (notice what the constructor accepts, and what methods the filter implements) <script src="https://gist.github.com/3022255.js?file=rack.rb"></script></p> <h2>Further Reading</h2> <ul><li><a href="http://en.wikipedia.org/wiki/Proxy_pattern">http://en.wikipedia.org/wiki/Proxy_pattern</a></li><li><a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">http://en.wikipedia.org/wiki/Aspect-oriented_programming</a></li></ul>gjahttp://www.blogger.com/profile/03096275805966250387noreply@blogger.com15