<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' 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-8968818456594497310</id><updated>2011-07-31T04:47:10.741-07:00</updated><category term='ruby'/><category term='emacs'/><category term='system software internals'/><category term='sql'/><category term='erlang'/><category term='common lisp'/><category term='rails'/><category term='stumpwm'/><title type='text'>Scribblings on Embedded Systems</title><subtitle type='html'>A blog on Embedded Systems, Computer Science and other 
interesting stuff.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://joelagnel.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://joelagnel.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Joel Fernandes</name><uri>http://www.blogger.com/profile/04997674848378795829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>11</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-8968818456594497310.post-4567476639835522336</id><published>2011-05-28T02:02:00.000-07:00</published><updated>2011-05-28T02:35:42.445-07:00</updated><title type='text'>Shutting down power to USB hosts on BeagleBoard-xM</title><content type='html'>So one of the things I want to do as a part of an idea one of colleagues suggested is to shut down power to the USB controller on my beagleboard-xM.&lt;br /&gt;&lt;br /&gt;There is a single chip in the beagleboard that provides power to the entire board (T&lt;br /&gt;MS65950) which provides power management apart from other things. The beauty of the design is all the supplies to this chip can be controlled over the I2C bus by the main processor.&lt;br /&gt;&lt;br /&gt;Architecture:&lt;br /&gt;Processor -&gt; USB PHY -&gt; USB HUB -&gt; USB ports&lt;br /&gt;&lt;br /&gt;There are 2 main power sources for 2 chips that are required for USB function.&lt;br /&gt;&lt;br /&gt;1. A 1.8v supply coming from directly from the power manager (TMS65950) to power the USB PHY. Why is a PHY required? Because the processor on its own cannot speak USB. It is like an ADC if you will.&lt;br /&gt;&lt;br /&gt;2. A 3.3v supply that powers the USB hub (SMSCLAN9514). This comes from an LDO which derives its power directly from the 5v rail (independent of the power manager). The beauty of the design is even though the LDO derives its power directly, it can still be controlled by the power manager which is inturn controllable over I2C bus by processor.&lt;br /&gt;&lt;br /&gt;Because the power manager has different power supplies for different uses (like for processor and peripherals), the processor can selectively shutdown power to different components. This is quite awesome. I guess this makes sense for an embedded board which would like to turn off power supplies that are not required.&lt;br /&gt;&lt;br /&gt;Infact- if you look at a PC architecture, it is not possible to shut down power to USB from kernel (if I'm right) unless your USB controller supports it. Not all devices support USB suspend mode and even if they did, the USB specification only says that they shouldn't draw more than a little current but technically no one is stopping them from drawing more :) In the case of beagleboard, we are strictly shutting down power supply.&lt;br /&gt;&lt;br /&gt;Next thing I have to figure out is how to do all this in software :)&lt;br /&gt;&lt;br /&gt;Thanks for reading, more updates coming.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8968818456594497310-4567476639835522336?l=joelagnel.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://joelagnel.blogspot.com/feeds/4567476639835522336/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8968818456594497310&amp;postID=4567476639835522336' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/4567476639835522336'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/4567476639835522336'/><link rel='alternate' type='text/html' href='http://joelagnel.blogspot.com/2011/05/shutting-down-power-to-usb-hosts-on.html' title='Shutting down power to USB hosts on BeagleBoard-xM'/><author><name>Joel Fernandes</name><uri>http://www.blogger.com/profile/04997674848378795829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8968818456594497310.post-2452753204871858214</id><published>2011-05-19T22:56:00.000-07:00</published><updated>2011-05-20T22:13:46.246-07:00</updated><title type='text'>BeagleBoard-xM</title><content type='html'>Just got a BeagleBoard-xM to play with and some time now that my exams are over (finally).&lt;br /&gt;&lt;br /&gt;It is a pretty nice board I must say, and I had it up and running in 15-20 minutes once I found the right cables in my lab.&lt;br /&gt;&lt;br /&gt;I'm a fan of X-windows so I decided to create a new X display just for the beagleboard and made Gnome running on the board connect to it over the wired network. It was fun!&lt;br /&gt;Here's a little demo: &lt;br /&gt;&lt;iframe class="youtube-player" type="text/html" width="640" height="385" src="http://www.youtube.com/embed/ViiTKvDoma4" frameborder="0"&gt;&lt;br /&gt;&lt;/iframe&gt;&lt;br /&gt;The performance of the board is amazing, considering it is tiny and fanless. Thanks to the low power of the OMAP3 processor, it can be powered completely through a mini USB cable. The processor is at 1GHz and it comes with plenty of RAM allowing you to &lt;a href="http://e2e.ti.com/blogs_/b/dlp_mems_blog/archive/2009/12/12/101-things-to-do-with-a-beagle-board.aspx"&gt;run a complete desktop environment&lt;/a&gt; and a few applications.&lt;br /&gt;&lt;br /&gt;There is also a fantastic opensource community and the documentation is fairly well written though its hard for anyone to keep it uptodate as the board evolves.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Storage&lt;/span&gt;&lt;br /&gt;The microSD card that came with it has all the images you need to test the board, though I am compiling my own kernel and U-boot to get my hands dirty. :)&lt;br /&gt;&lt;br /&gt;It doesn't come with any NAND flash though so it relies on bootloading from a microSD card. If I'm right - the Boot ROM expects the boot partition to be FAT32 (I guess because reading FAT32 takes little code) from where it loads X-loader to kick start the boot loading process.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Ethernet and USB&lt;/span&gt;&lt;br /&gt;The -xM comes with an integrated USB hub (SMSC LAN514) chip with support for 4 USB ports. The chip also has integrated Ethernet support with a complete 802.3 MAC and PHY. Isn't that cool!&lt;br /&gt;&lt;br /&gt;Obviously there is a lot more to explore. More information: &lt;a href="http://www.beagleboard.org/"&gt;http://www.beagleboard.org/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Extra Notes:&lt;/span&gt;&lt;br /&gt;1. How to get an X-windows session with the beagleboard:&lt;br /&gt;&lt;br /&gt;On the X-server:&lt;br /&gt;&lt;pre&gt;/usr/bin/X :1 -br -v      # X server instance on display 1&lt;br /&gt;DISPLAY=:1 xhost +        # Permission for the board to connect&lt;/pre&gt;On the Beagle Board:&lt;br /&gt;&lt;pre&gt;DISPLAY=joel:1 gnome-session # DISPLAY = X-server's host:display-name&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Next:&lt;/span&gt;&lt;br /&gt;I'm going to try building my own Xloader, Kernel and U-boot. I will most likely boot from NFS as I don't like ejecting and copying stuff to the microSD card which is quite tiny for my fingers. :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8968818456594497310-2452753204871858214?l=joelagnel.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://joelagnel.blogspot.com/feeds/2452753204871858214/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8968818456594497310&amp;postID=2452753204871858214' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/2452753204871858214'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/2452753204871858214'/><link rel='alternate' type='text/html' href='http://joelagnel.blogspot.com/2011/05/beagleboard-xm.html' title='BeagleBoard-xM'/><author><name>Joel Fernandes</name><uri>http://www.blogger.com/profile/04997674848378795829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://img.youtube.com/vi/ViiTKvDoma4/default.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8968818456594497310.post-7328743362895552847</id><published>2010-06-12T23:36:00.000-07:00</published><updated>2010-06-13T08:28:42.131-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='system software internals'/><title type='text'>An introductory guide to linking and loading</title><content type='html'>So I decided to remove the post on dynamic linking because it was largely useless to everyone but myself, and I wanted to get into some serious writing on linking and loading mechanisms, and needed an excuse to learn LaTeX. ;-)&lt;br /&gt;&lt;br /&gt;So I'll be working on a guide I'm calling "Gentle Introduction to Linking and Loading"&lt;br /&gt;&lt;br /&gt;Will take material from the previous posts, edit it and add some more with nice examples and figures. This is a work in progress and will probably take a very long time to complete.&lt;br /&gt;&lt;br /&gt;You can pull LaTeX sources of the work &lt;a href="http://github.com/joelagnel/gill"&gt;here&lt;/a&gt; or &lt;a href="http://joelagnel.github.com/gill/main.pdf"&gt;read it online&lt;/a&gt;. Ofcourse its all bits and pieces for now but I want to get some early feedback.&lt;br /&gt;&lt;br /&gt;Your comments are much appreciated :) and if there's anything missing or you would like to contribute any part of it, I would love to hear from you.&lt;br /&gt;&lt;br /&gt;Thanks&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8968818456594497310-7328743362895552847?l=joelagnel.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://joelagnel.blogspot.com/feeds/7328743362895552847/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8968818456594497310&amp;postID=7328743362895552847' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/7328743362895552847'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/7328743362895552847'/><link rel='alternate' type='text/html' href='http://joelagnel.blogspot.com/2010/06/introductory-guide-to-linker-loader.html' title='An introductory guide to linking and loading'/><author><name>Joel Fernandes</name><uri>http://www.blogger.com/profile/04997674848378795829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8968818456594497310.post-5779818296319577227</id><published>2009-11-22T01:46:00.000-08:00</published><updated>2010-02-28T11:44:52.947-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='system software internals'/><title type='text'>C Programming: Understanding function calls</title><content type='html'>Today I had some fun playing with assembly to understand the mechanics of function calls and parameter passing on x86.&lt;br /&gt;&lt;br /&gt;The C Program:&lt;br /&gt;&lt;pre&gt;#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;void func1(int a)&lt;br /&gt;{&lt;br /&gt;        printf("hey there, I'm in func1! %d\n", a);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;void func0()&lt;br /&gt;{&lt;br /&gt;        printf("hey there, I'm in func0!");&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main()&lt;br /&gt;{&lt;br /&gt;        func0();  /* Pass no arguments */&lt;br /&gt;        func1(1); /* Pass 1 argument */&lt;br /&gt;        return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Next I compiled and disassembled this:&lt;br /&gt;&lt;pre&gt;gcc -o func.c func&lt;br /&gt;objdump -d -M intel func &gt; func.dump&lt;/pre&gt;&lt;br /&gt;Disassembled Output (heavily commented):&lt;br /&gt;&lt;pre&gt;;;;;;;;;;;;;; func1 disassembled ;;;;;;;;;;;;;;;&lt;br /&gt;080483c4 (func1):&lt;br /&gt; ; Save the calling func's stack frame pointer.&lt;br /&gt; 80483c4:       55                      push   ebp &lt;br /&gt;&lt;br /&gt; ; Create the stack frame pointer for this function. This will be used later as&lt;br /&gt; ; a reference point from which the arguments that were just pushed to stack&lt;br /&gt; ; from the main function can be retrieved (see main function below)&lt;br /&gt; 80483c5:       89 e5                   mov    ebp,esp  &lt;br /&gt;&lt;br /&gt; ; Allocate space on the stack for local variables.&lt;br /&gt; 80483c7:       83 ec 08                sub    esp,0x8 &lt;br /&gt;&lt;br /&gt; ; Fetch the argument passed from calling function (integer 1)&lt;br /&gt; ; We add 8 to ebp because we need to go back in the stack to a point where&lt;br /&gt; ; we can fetch the argument being passed. Its 8 because we used 4 while&lt;br /&gt; ; pushing ebp (above) and 4 more because the calling function pushed the&lt;br /&gt; ; address of the instruction to be executed after this function returns.&lt;br /&gt; 80483ca:       8b 45 08                mov    eax,DWORD PTR [ebp+0x8]&lt;br /&gt;&lt;br /&gt; ; Store the fetched argument on the stack (to be passed to printf).&lt;br /&gt; 80483cd:       89 44 24 04             mov    DWORD PTR [esp+0x4],eax&lt;br /&gt;&lt;br /&gt; ; Store the address of the string on the stack (to be passed to printf).&lt;br /&gt; ; This string is stored in the ".rodata" section of the executable file.&lt;br /&gt; 80483d1:       c7 04 24 f0 84 04 08    mov    DWORD PTR [esp],0x80484f0&lt;br /&gt;&lt;br /&gt; ; Call the function to format/print the text.&lt;br /&gt; 80483d8:       e8 1b ff ff ff          call   80482f8 &lt;printf@plt&gt; &lt;br /&gt;&lt;br /&gt; ; Restore the frame pointer (ebp) to its original value and return.&lt;br /&gt; 80483dd:       c9                      leave    &lt;br /&gt; 80483de:       c3                      ret    &lt;br /&gt;&lt;br /&gt;; func0 is the same as func1 except we don't need to fetch the integer&lt;br /&gt;; and store it on the stack.&lt;br /&gt;080483df (func0):     &lt;br /&gt; 80483df:       55                      push   ebp &lt;br /&gt; ; .. skipped ..&lt;br /&gt;&lt;br /&gt;;;;;;;;;;;;;; main function disassembled ;;;;;;;;;;;;;;;&lt;br /&gt;080483f3 (main):&lt;br /&gt; 80483f3:       8d 4c 24 04             lea    ecx,[esp+0x4]&lt;br /&gt; 80483f7:       83 e4 f0                and    esp,0xfffffff0&lt;br /&gt; 80483fa:       ff 71 fc                push   DWORD PTR [ecx-0x4]&lt;br /&gt; 80483fd:       55                      push   ebp&lt;br /&gt; 80483fe:       89 e5                   mov    ebp,esp&lt;br /&gt; 8048400:       51                      push   ecx&lt;br /&gt; ; Allocate space on stack for local variables/args.&lt;br /&gt; 8048401:       83 ec 04                sub    esp,0x4&lt;br /&gt;&lt;br /&gt; ; Call func0 (no arguments, nothing on our stack).&lt;br /&gt; 8048404:       e8 d6 ff ff ff          call   80483df &lt;func0&gt;&lt;br /&gt;&lt;br /&gt; ; Store the integer 1 on stack which will be retrieved by the function func1.&lt;br /&gt; 8048409:       c7 04 24 01 00 00 00    mov    DWORD PTR [esp],0x1 &lt;br /&gt; 8048410:       e8 af ff ff ff          call   80483c4 &lt;func1&gt;&lt;br /&gt;&lt;br /&gt; ; This I'm guess is the return value of the main funciton.&lt;br /&gt; 8048415:       b8 00 00 00 00          mov    eax,0x0&lt;br /&gt;&lt;br /&gt; ; Relinquish allocated stack space.&lt;br /&gt; 804841a:       83 c4 04                add    esp,0x4     &lt;br /&gt;&lt;br /&gt; ; Restore the contents of registers and the stack frame pointer (ebp).&lt;br /&gt; 804841d:       59                      pop    ecx     &lt;br /&gt; 804841e:       5d                      pop    ebp&lt;br /&gt; 804841f:       8d 61 fc                lea    esp,[ecx-0x4]&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Learning assembly is fun and can further your understanding at a much deeper level.&lt;br /&gt;I highly recommend &lt;a href="http://programminggroundup.blogspot.com"&gt;Programming from the ground up&lt;/a&gt; for an introduction to programming, assembly and linux.&lt;br /&gt;&lt;br&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8968818456594497310-5779818296319577227?l=joelagnel.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://joelagnel.blogspot.com/feeds/5779818296319577227/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8968818456594497310&amp;postID=5779818296319577227' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/5779818296319577227'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/5779818296319577227'/><link rel='alternate' type='text/html' href='http://joelagnel.blogspot.com/2009/11/exercise-understanding-function-call.html' title='C Programming: Understanding function calls'/><author><name>Joel Fernandes</name><uri>http://www.blogger.com/profile/04997674848378795829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8968818456594497310.post-5586759348228165301</id><published>2009-02-28T21:27:00.000-08:00</published><updated>2010-02-28T11:44:16.744-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='common lisp'/><title type='text'>Functions with Pattern Matching arguments in Common Lisp.</title><content type='html'>I recently stumbled upon a cool CL library that makes it possible to define functions with pattern-matching arguments (like how its done in Haskell/Erlang). This is particularly useful and elegant, there are numerous benefits to your Language supporting pattern matching function arguments. The most important according to me are conciseness, elegance and clarity. Slava articulates this very well &lt;a href="http://www.defmacro.org/ramblings/fp.html"&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Why I love pattern matching:&lt;/b&gt;&lt;br /&gt;- Pattern matching makes it very easy to write recursive programs. For example, for terminating the recursion, traditionally you'd have to wrap your terminating condition (for example, (equal list1 nil)) in a cond or if, and manually test it during every recursive call. That's something you'd hate doing if you've ever written programs in Erlang or Haskell.&lt;br /&gt;- I frequently write programs that progressively destructure lists, and having to pull out the car of a car of a car, can be a pain sometimes. With pattern matching, I can have these pulled out and bound to variables - automatically.&lt;br /&gt;&lt;br /&gt;Unfortunately, Common Lisp doesn't have such a notion built into it (some people talk about Destructuring bind. Please, it works only for macro parameters, not functions. and is very limited in what it can do (in this context)).&lt;br /&gt;&lt;br /&gt;To see just how nice pattern matching is and why it would suck if your language didn't or couldn't have it, consider the classical factorial example in Common Lisp and its erlang equivalent:&lt;br /&gt;&lt;b&gt;Common Lisp:&lt;/b&gt;&lt;pre&gt;&lt;br /&gt;(&lt;span class="keyword"&gt;defun&lt;/span&gt; &lt;span class="function-name"&gt;fact&lt;/span&gt;(n)&lt;br /&gt;  (&lt;span class="keyword"&gt;cond&lt;/span&gt; ((equal n 0) 1)&lt;br /&gt;        ((&amp;gt; n 0) (* n&lt;br /&gt;                    (fact (- n 1))))))&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;b&gt;Erlang:&lt;/b&gt;&lt;pre&gt;&lt;br /&gt;&lt;span class="function-name"&gt;fact&lt;/span&gt;(0) &lt;span class="function-name"&gt;-&amp;gt;&lt;/span&gt; 1;&lt;br /&gt;&lt;span class="function-name"&gt;fact&lt;/span&gt;(&lt;span class="variable-name"&gt;N&lt;/span&gt;) &lt;span class="function-name"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="variable-name"&gt;N&lt;/span&gt; * fact(&lt;span class="variable-name"&gt;N&lt;/span&gt; - 1).&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;Erlang clearly wins, the code is much more readable and elegant than the common lisp version. Lisp with an evil grin, says, hold it right there! and pulls out a cool library from its arsenal called &lt;a href="http://common-lisp.net/project/bpm/"&gt;&lt;b&gt;bpm&lt;/b&gt;&lt;/a&gt;. Its really cool in that its written entirely in Portable Common Lisp and is yet another example of how powerful lisp can be in extending itself. With bpm, you can now define your lisp functions with arguments that pattern match and bind to variables.. just like how you would in Erlang/Haskell.&lt;br /&gt;&lt;br /&gt;Some examples in Common Lisp to show you how clean your code will look:&lt;br /&gt;&lt;b&gt;Factorial:&lt;/b&gt;&lt;pre&gt;&lt;br /&gt;(&lt;span class="keyword"&gt;def!&lt;/span&gt; &lt;span class="function-name"&gt;fact&lt;/span&gt; (0)  1)&lt;br /&gt;(&lt;span class="keyword"&gt;def&lt;/span&gt;  &lt;span class="function-name"&gt;fact&lt;/span&gt; (_n) (* _n&lt;br /&gt;                   (fact (- _n 1))))&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;b&gt;Fibonacci of a number:&lt;/b&gt;&lt;pre&gt;&lt;br /&gt;(&lt;span class="keyword"&gt;def!&lt;/span&gt; &lt;span class="function-name"&gt;fib&lt;/span&gt; (0) 0)&lt;br /&gt;(&lt;span class="keyword"&gt;def&lt;/span&gt;  &lt;span class="function-name"&gt;fib&lt;/span&gt; (1) 1)&lt;br /&gt;(&lt;span class="keyword"&gt;def&lt;/span&gt;  &lt;span class="function-name"&gt;fib&lt;/span&gt; (_n) (+ (fib (- _n 1))&lt;br /&gt;                  (fib (- _n 2))))&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;It gets even better when you have to destructure lists recursively:&lt;br /&gt;&lt;b&gt;A function that adds all the elements of a list:&lt;/b&gt;&lt;pre&gt;&lt;br /&gt;(&lt;span class="keyword"&gt;def!&lt;/span&gt; &lt;span class="function-name"&gt;myf1&lt;/span&gt; () 0)&lt;br /&gt;(&lt;span class="keyword"&gt;def &lt;/span&gt; &lt;span class="function-name"&gt;myf1&lt;/span&gt; (_head . _tail)&lt;br /&gt;  (+ _head (myf1 _tail)))&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;Sweet! :)&lt;br&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8968818456594497310-5586759348228165301?l=joelagnel.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://joelagnel.blogspot.com/feeds/5586759348228165301/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8968818456594497310&amp;postID=5586759348228165301' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/5586759348228165301'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/5586759348228165301'/><link rel='alternate' type='text/html' href='http://joelagnel.blogspot.com/2009/02/functions-with-pattern-matching.html' title='Functions with Pattern Matching arguments in Common Lisp.'/><author><name>Joel Fernandes</name><uri>http://www.blogger.com/profile/04997674848378795829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8968818456594497310.post-509089487766382535</id><published>2009-01-25T06:19:00.000-08:00</published><updated>2009-02-25T21:44:04.762-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='erlang'/><title type='text'>Erlang: A Dynamic Controllable Timer</title><content type='html'>Here's a modified version of the Timer example in Joe Amstrong's great book "Programming Erlang"&lt;br /&gt;Joe talks about spawning processes and receiving messages with timeouts, and then goes about building a timer using these concepts. This version makes it a bit more dynamic and self-changing according to messages you send the timer once you create it.&lt;br /&gt;It also shows how you can use recursion to build a periodic timer..&lt;br /&gt;&lt;br /&gt;Code:    &lt;pre&gt;&lt;br /&gt;&lt;span class="function-name"&gt;-module&lt;/span&gt;(xtimer).&lt;br /&gt;&lt;span class="function-name"&gt;-export&lt;/span&gt;([make/2]).&lt;br /&gt;&lt;br /&gt;&lt;span class="function-name"&gt;make&lt;/span&gt;(&lt;span class="variable-name"&gt;Period&lt;/span&gt;, &lt;span class="variable-name"&gt;Message&lt;/span&gt;) &lt;span class="function-name"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="keyword"&gt;spawn&lt;/span&gt;(&lt;span class="keyword"&gt;fun&lt;/span&gt; () &lt;span class="function-name"&gt;-&amp;gt;&lt;/span&gt; start(&lt;span class="variable-name"&gt;Period&lt;/span&gt;, &lt;span class="variable-name"&gt;Message&lt;/span&gt;) &lt;span class="keyword"&gt;end&lt;/span&gt;).&lt;br /&gt;&lt;br /&gt;&lt;span class="function-name"&gt;start&lt;/span&gt;(&lt;span class="variable-name"&gt;Period&lt;/span&gt;, &lt;span class="variable-name"&gt;Message&lt;/span&gt;) &lt;span class="function-name"&gt;-&amp;gt;&lt;/span&gt;&lt;br /&gt;    &lt;span class="keyword"&gt;receive&lt;/span&gt;&lt;br /&gt;        &lt;span class="variable-name"&gt;NewMessage&lt;/span&gt; &lt;span class="keyword"&gt;when&lt;/span&gt; &lt;span class="constant"&gt;is_list&lt;/span&gt;(&lt;span class="variable-name"&gt;NewMessage&lt;/span&gt;)  &lt;span class="function-name"&gt;-&amp;gt;&lt;/span&gt; start(&lt;span class="variable-name"&gt;Period&lt;/span&gt;, &lt;span class="variable-name"&gt;NewMessage&lt;/span&gt;);&lt;br /&gt;        &lt;span class="variable-name"&gt;NewPeriod&lt;/span&gt;  &lt;span class="keyword"&gt;when&lt;/span&gt; &lt;span class="constant"&gt;is_number&lt;/span&gt;(&lt;span class="variable-name"&gt;NewPeriod&lt;/span&gt;) &lt;span class="function-name"&gt;-&amp;gt;&lt;/span&gt; start(&lt;span class="variable-name"&gt;NewPeriod&lt;/span&gt;, &lt;span class="variable-name"&gt;Message&lt;/span&gt;)&lt;br /&gt;    &lt;span class="keyword"&gt;after&lt;/span&gt; &lt;span class="variable-name"&gt;Period&lt;/span&gt; &lt;span class="function-name"&gt;-&amp;gt;&lt;/span&gt;&lt;br /&gt;        io:format(&lt;span class="string"&gt;"~p~n"&lt;/span&gt;, [&lt;span class="variable-name"&gt;Message&lt;/span&gt;]),&lt;br /&gt;        start(&lt;span class="variable-name"&gt;Period&lt;/span&gt;, &lt;span class="variable-name"&gt;Message&lt;/span&gt;)&lt;br /&gt;    &lt;span class="keyword"&gt;end&lt;/span&gt;.&lt;br /&gt;&lt;/pre&gt;Explanation:&lt;br /&gt;1. The first 2 lines are self-explanatory&lt;br /&gt;2. The make function is what we call from the shell and it spawns a timer which prints Message every Period milliseconds. Make also returns the timer's Pid which we use to control it.&lt;br /&gt;3. We then send messages to our timer using its Pid to change its behaviour (Message/Period).&lt;br /&gt;&lt;br /&gt;everytime you need to change the timer properties, No need to stop and restart, just send it a message! try doing that in any other language :-)&lt;br /&gt;&lt;br /&gt;Test run..    &lt;pre&gt;&lt;br /&gt;&lt;span class="variable-name"&gt;Eshell&lt;/span&gt; &lt;span class="variable-name"&gt;V5&lt;/span&gt;.5.5  (abort with ^&lt;span class="variable-name"&gt;G&lt;/span&gt;)&lt;br /&gt;2&amp;gt; &lt;span class="variable-name"&gt;Timer&lt;/span&gt; = xtimer:make(2000, &lt;span class="string"&gt;"Joel loves erlang!"&lt;/span&gt;).&lt;br /&gt;&amp;lt;0.38.0&amp;gt;&lt;br /&gt;&lt;span class="string"&gt;"Joel loves erlang!"&lt;/span&gt;&lt;br /&gt;&lt;span class="string"&gt;"Joel loves erlang!"&lt;/span&gt;&lt;br /&gt;&lt;span class="string"&gt;"Joel loves erlang!"&lt;/span&gt;&lt;br /&gt;&lt;span class="string"&gt;"Joel loves erlang!"&lt;/span&gt;&lt;br /&gt;&lt;span class="string"&gt;"Joel loves erlang!"&lt;/span&gt;&lt;br /&gt;3&amp;gt; &lt;span class="variable-name"&gt;Timer&lt;/span&gt; ! &lt;span class="string"&gt;"Timer message changes...."&lt;/span&gt;.&lt;br /&gt;&lt;span class="string"&gt;"Timer message changes...."&lt;/span&gt;&lt;br /&gt;&lt;span class="string"&gt;"Timer message changes...."&lt;/span&gt;&lt;br /&gt;&lt;span class="string"&gt;"Timer message changes...."&lt;/span&gt;&lt;br /&gt;&lt;span class="string"&gt;"Timer message changes...."&lt;/span&gt;&lt;br /&gt;&lt;span class="string"&gt;"Timer message changes...."&lt;/span&gt;&lt;br /&gt;4&amp;gt; &lt;span class="variable-name"&gt;Timer&lt;/span&gt; ! 3000.     &lt;span class="comment-delimiter"&gt;% &lt;/span&gt;&lt;span class="comment"&gt;Timer is now slower...&lt;br /&gt;&lt;/span&gt;3000&lt;br /&gt;&lt;span class="string"&gt;"Timer message changes...."&lt;/span&gt;&lt;br /&gt;&lt;span class="string"&gt;"Timer message changes...."&lt;/span&gt;&lt;br /&gt;&lt;span class="string"&gt;"Timer message changes...."&lt;/span&gt;&lt;br /&gt;5&amp;gt; q().&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8968818456594497310-509089487766382535?l=joelagnel.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://joelagnel.blogspot.com/feeds/509089487766382535/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8968818456594497310&amp;postID=509089487766382535' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/509089487766382535'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/509089487766382535'/><link rel='alternate' type='text/html' href='http://joelagnel.blogspot.com/2009/01/erlang-dynamic-controllable-timer.html' title='Erlang: A Dynamic Controllable Timer'/><author><name>Joel Fernandes</name><uri>http://www.blogger.com/profile/04997674848378795829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8968818456594497310.post-8873970956230180584</id><published>2008-11-09T08:50:00.000-08:00</published><updated>2009-02-25T21:41:21.692-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='stumpwm'/><category scheme='http://www.blogger.com/atom/ns#' term='emacs'/><title type='text'>stumpwm mail/message notifications from Emacs Jabber - walkthrough</title><content type='html'>Over the weekend, I got to install the &lt;a href="http://www.nongnu.org/stumpwm/index.html"&gt;stumpwm window manager&lt;/a&gt; on SBCL, and its absolutely brilliant. A tiling, fully keyboard controlled extensible window manager.&lt;br /&gt;I also got to get &lt;a href="http://common-lisp.net/project/slime/"&gt;SLIME&lt;/a&gt; up and running which gives me direct access to the running stumpw process, I can directly eval code from emacs/slime and change the behavior of the window manager, very neat indeed. &lt;br /&gt;&lt;br /&gt;For starters, I added all a lot of stuff to the mode line, with my hostname, battery charge, date, IP address etc. The best part, I was able to make emacs talk to stumpwm through slime, so I thought I might as well go ahead and integrate jabber.el and jabber-mail-notify.el (which notifies emacs of new mail) to the stumpwm modeline and message bar.&lt;br /&gt;&lt;br /&gt;The initial model I adopted was&lt;PRE&gt;Emacs Jabber -&gt; Slime -&gt; Stumpwm (swank loaded) -&gt; Stumpwm modeline/message-bar.&lt;/PRE&gt;The drawback was I always had to startup swank and slime-connect to it from emacs before sending any messages to stumpwm. So I adopted a flat file approach (emacs talking to stumpwm through flat files), which turned out to be very quicky and efficient.&lt;PRE&gt;Emacs Jabber -&gt; File write -&gt; Stumpwm File read -&gt; Update sumpwm modeline/message-bar.&lt;/PRE&gt;The result was neat and working (see screen shots at the end)&lt;br&gt;&lt;b&gt;Here's how I did it:&lt;/b&gt;&lt;br /&gt;Firstly you will need &lt;a href="http://atlantisbangalore.selfip.com/~joel/projects/jabber-mail-notify.html"&gt;jabber-mail-notify.el&lt;/a&gt; (an extension I wrote last week to notify emacs jabber of new google mail messages).&lt;br /&gt;Once you have emacs jabber, with jabber-mail-notify.el in place, add the following to your emacs de-jabber.el init file:&lt;br&gt;(this code registers 2 emacs jabber hooks, one for new chat requests, and the second for new mail.)    &lt;pre&gt;&lt;br /&gt;&lt;span class="comment-delimiter"&gt;;; &lt;/span&gt;&lt;span class="comment"&gt;Stumpwm new message mode-line integration&lt;br /&gt;&lt;/span&gt;(&lt;span class="keyword"&gt;defun&lt;/span&gt; &lt;span class="function-name"&gt;jabber-stumpwm-activity-modeline-update&lt;/span&gt; ()&lt;br /&gt;  (&lt;span class="keyword"&gt;let&lt;/span&gt; ((text jabber-activity-mode-string))&lt;br /&gt;    (&lt;span class="keyword"&gt;if&lt;/span&gt; (not (eq (length text) 0))&lt;br /&gt;        (setf text (concat &lt;span class="string"&gt;" [Message from "&lt;/span&gt; text &lt;span class="string"&gt;"]"&lt;/span&gt;)))&lt;br /&gt;    (write-string-to-file &lt;span class="string"&gt;"~/emacs-jabber.temp"&lt;/span&gt; text)&lt;br /&gt;    (princ &lt;span class="string"&gt;"Done."&lt;/span&gt;)))&lt;br /&gt;(add-hook 'jabber-activity-update-hook 'jabber-stumpwm-activity-modeline-update)&lt;br /&gt;&lt;br /&gt;&lt;span class="comment-delimiter"&gt;;; &lt;/span&gt;&lt;span class="comment"&gt;Stumpwm new mail mode-line integration&lt;br /&gt;&lt;/span&gt;(&lt;span class="keyword"&gt;defun&lt;/span&gt; &lt;span class="function-name"&gt;jabber-mail-stumpwm-mode-line-update&lt;/span&gt;(iq-data)&lt;br /&gt;  (&lt;span class="keyword"&gt;let*&lt;/span&gt; ((text (jabber-build-mailbox-string iq-data)))&lt;br /&gt;    (write-string-to-file &lt;span class="string"&gt;"~/emacs-jabber-mail.temp"&lt;/span&gt; text)&lt;br /&gt;    text)&lt;br /&gt;  (princ &lt;span class="string"&gt;"Done."&lt;/span&gt;))&lt;br /&gt;(add-hook 'jabber-mail-notification-hook 'jabber-mail-stumpwm-mode-line-update)&lt;br /&gt;&lt;span class="comment-delimiter"&gt;;; &lt;/span&gt;&lt;span class="comment"&gt;-------------------------------------------&lt;/span&gt;&lt;/pre&gt;Now lets make stumpwm periodically read the temporary files for any mail/chat updates using the unix cat command.&lt;br /&gt;Add the following to your ~/.stumprc or wherever you initialize your mode line format:    &lt;pre&gt;&lt;br /&gt;(&lt;span class="keyword"&gt;in-package&lt;/span&gt; stumpwm)&lt;br /&gt;(&lt;span class="keyword"&gt;defun&lt;/span&gt; &lt;span class="function-name"&gt;show-emacs-jabber-new-message&lt;/span&gt; ()&lt;br /&gt;  (&lt;span class="keyword"&gt;let&lt;/span&gt; ((new-message (run-shell-command &lt;span class="string"&gt;"cat ~/emacs-jabber.temp"&lt;/span&gt; t)))&lt;br /&gt;    (substitute #\Space #\Newline new-message)))&lt;br /&gt;&lt;br /&gt;(&lt;span class="keyword"&gt;defun&lt;/span&gt; &lt;span class="function-name"&gt;show-emacs-jabber-new-mail&lt;/span&gt; ()&lt;br /&gt;  (&lt;span class="keyword"&gt;let&lt;/span&gt; ((new-mail (run-shell-command &lt;span class="string"&gt;"cat ~/emacs-jabber-mail.temp"&lt;/span&gt; t)))&lt;br /&gt;    (&lt;span class="keyword"&gt;if&lt;/span&gt; (not (eq (length new-mail) 0))&lt;br /&gt;        (&lt;span class="keyword"&gt;progn&lt;/span&gt; (stumpwm:message new-mail)&lt;br /&gt;               (run-shell-command &lt;span class="string"&gt;"rm ~/emacs-jabber-mail.temp"&lt;/span&gt; t)&lt;br /&gt;               (run-shell-command &lt;span class="string"&gt;"touch ~/emacs-jabber-mail.temp"&lt;/span&gt; t)))&lt;br /&gt;    &lt;span class="string"&gt;""&lt;/span&gt;))&amp;lt;/PRE&amp;gt;Lastly modify your *screen-mode-line-format* variable such that it includes the following bolded elements at the end of the list.&amp;lt;PRE&amp;gt;(&lt;span class="keyword"&gt;in-package&lt;/span&gt; stumpwm)&lt;br /&gt;&lt;span class="comment-delimiter"&gt;;; &lt;/span&gt;&lt;span class="comment"&gt;Set mode-line format&lt;br /&gt;&lt;/span&gt;(setf *screen-mode-line-format*&lt;br /&gt;      (list&lt;br /&gt;       '(&lt;span class="builtin"&gt;:eval&lt;/span&gt; (show-hostname))&lt;br /&gt;       &lt;span class="string"&gt;"| Battery:"&lt;/span&gt;&lt;br /&gt;       '(&lt;span class="builtin"&gt;:eval&lt;/span&gt; (show-battery-charge))&lt;br /&gt;       '(&lt;span class="builtin"&gt;:eval&lt;/span&gt; (show-battery-state))&lt;br /&gt;       &lt;span class="string"&gt;"| IP "&lt;/span&gt; '(&lt;span class="builtin"&gt;:eval&lt;/span&gt; (show-ip-address))&lt;br /&gt;       &lt;span class="string"&gt;"| "&lt;/span&gt; '(&lt;span class="builtin"&gt;:eval&lt;/span&gt; (run-shell-command &lt;span class="string"&gt;"ruby -e \"print Time.now\""&lt;/span&gt; t))&lt;br /&gt;    '(&lt;span class="builtin"&gt;:eval&lt;/span&gt; (show-emacs-jabber-new-message))&lt;br /&gt;    '(&lt;span class="builtin"&gt;:eval&lt;/span&gt; (show-emacs-jabber-new-mail))))&lt;/pre&gt;That should make your modeline periodically call those methods you just added. ..Done. restart stumpwm and emacs jabber, and you should be good. If you're smart, you can use slime, and ielm, and eval everything on the fly, without any restarts. That's the beauty of emacs and stumpwm! dynamic runtime evaluation is beautiful.&lt;br /&gt;With the above code in place now, I can receive notifications of new mail, and chat messages from any window/frame/group of stumpwm. This is very handy for me as I no longer would silently ignore chat/mail notifications from emacs jabber just because I was on some other window/group.&lt;br /&gt;If you hit any problem, feel free to mail or message me, now that I have the stump / emacs-jabber integrated, I will instantly get your message. :)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Screen shots (click to view larger):&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;stumpwm modeline getting updated with a new chat notification by emacs-jabber:&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_7ik9UEnRBS4/SRcpgNpNZTI/AAAAAAAAALg/Is6sE8c0BKQ/s1600-h/message-notify.png"&gt;&lt;img style="cursor:pointer; cursor:hand;width: 400px; height: 52px;" src="http://3.bp.blogspot.com/_7ik9UEnRBS4/SRcpgNpNZTI/AAAAAAAAALg/Is6sE8c0BKQ/s400/message-notify.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5266723922628142386" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;stumpwm message bar updated with a new mail message notification by emacs-jabber:&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://4.bp.blogspot.com/_7ik9UEnRBS4/SRco_PiqFzI/AAAAAAAAALY/uXI4mjQpJYs/s1600-h/stumpwm-newmail-screen1.jpg"&gt;&lt;img style="cursor:pointer; cursor:hand;width: 320px; height: 111px;" src="http://4.bp.blogspot.com/_7ik9UEnRBS4/SRco_PiqFzI/AAAAAAAAALY/uXI4mjQpJYs/s320/stumpwm-newmail-screen1.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5266723356201850674" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;stumpwm message bar updated with a list of unread email on connecting to jabber:&lt;br /&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://1.bp.blogspot.com/_7ik9UEnRBS4/SRcoIRXmdFI/AAAAAAAAALQ/8tbBQ-LWAec/s1600-h/stumpwm-newmail-screen.jpg"&gt;&lt;img style="cursor:pointer; cursor:hand;width: 400px; height: 162px;" src="http://1.bp.blogspot.com/_7ik9UEnRBS4/SRcoIRXmdFI/AAAAAAAAALQ/8tbBQ-LWAec/s400/stumpwm-newmail-screen.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5266722411799540818" /&gt;&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8968818456594497310-8873970956230180584?l=joelagnel.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://joelagnel.blogspot.com/feeds/8873970956230180584/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8968818456594497310&amp;postID=8873970956230180584' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/8873970956230180584'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/8873970956230180584'/><link rel='alternate' type='text/html' href='http://joelagnel.blogspot.com/2008/11/stumpwm-new-mail-and-new-message.html' title='stumpwm mail/message notifications from Emacs Jabber - walkthrough'/><author><name>Joel Fernandes</name><uri>http://www.blogger.com/profile/04997674848378795829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/_7ik9UEnRBS4/SRcpgNpNZTI/AAAAAAAAALg/Is6sE8c0BKQ/s72-c/message-notify.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8968818456594497310.post-5694710153594364993</id><published>2008-11-01T23:44:00.000-07:00</published><updated>2009-01-25T22:11:27.456-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='emacs'/><title type='text'>my first emacs extension - A google mail notifier for Jabber</title><content type='html'>Google talk's XMPP protocol has a few nice extensions to the standard XMPP, one of them being new mail notifications. So for all those google talk lovers, now you can receive email notification, using my new emacs extension (very-very-easy-to-install):&lt;pre&gt;&lt;a href="http://atlantisbangalore.selfip.com/~joel/projects/jabber-mail-notify.html"&gt;http://atlantisbangalore.selfip.com/~joel/projects/jabber-mail-notify.html&lt;/a&gt;&lt;/pre&gt;&lt;h4&gt;Hacking an Art&lt;/h4&gt;Hacking is an art, where you take existing stuff, reuse it, add your own stuff to it, read docs, manuals whatever you can get your hands on, look for pieces of information and code examples that are critical to solving your problem or accomplishing your objective. Most important of all, having fun while doing it!&lt;br /&gt;&lt;br /&gt;For the emacs jabber extension, the following helped me a great deal:&lt;br /&gt;- &lt;a href="http://emacs-jabber.sourceforge.net/manual-0.7.1/index.html"&gt;The Emacs jabber docs&lt;/a&gt;&lt;br /&gt;- &lt;a href="http://code.google.com/apis/talk/jep_extensions/gmail.html"&gt;Google talk's XMPP extensions&lt;/a&gt;&lt;br /&gt;- The most powerful development environment (Emacs !!)&lt;br /&gt;- A knowledge of Common Lisp&lt;h4&gt;The power of emacs as an emacs-lisp development environment. &lt;/h4&gt;The fact that emacs allows you to eval code that changes its behavior on the fly while its running is simply a big win. Its simply something that has led to its success, and the huge emacs code base that there is today.&lt;h4&gt;Bottom Up programming approach.&lt;/h4&gt;For every function that I wrote, I was able to test whether it did what it was supposed to by evaluating it at point. (C-x C-e). That way, I was confident as I wrote the program, that I wouldn't need to go back and debug it. I even forgot about the code as I wrote it, and as it got progressively more complicated. The reason I found it okay to forget about the code I had already written was I wrote the extension using a bottom up programming style.&lt;h4&gt;The 2 pieces of the puzzle&lt;/h4&gt;I independently worked on 2 separate parts of the extension.&lt;br /&gt;1. Getting google to send me notifications and understanding the response.&lt;br /&gt;   Fetching new unread mail.&lt;br /&gt;2. Parsing google's XML response and formatting it for display.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;The first part: &lt;/b&gt;The first part was easy thanks to the dynamic emacs programming environment, which allows you to eval code on the fly. By writing dummy samples of code, I was able to understand how the whole XMPP communication works, the data that google sends to me and that it expects me to respond with. I was able to test my functions, on the fly and see google's jabber server response in the emacs jabber xml logs. It felt like a pilot, pushing the joysticks and seeing the plane respond. That is what I call fun!!&lt;br /&gt;&lt;br /&gt;&lt;b&gt;The second part: &lt;/b&gt;Fetching the data was a small part of the deal. The XML returned by google is fairly complex, and I had before me the myriad task of parsing that huge bunch of gibberish thrown at my screen! I will spare the details, but trust me it really looked ugly. :-) Lisp being a functional language - &lt;a href="http://www.paulgraham.com/progbot.html"&gt;bottom-up programming&lt;/a&gt; is natural and easy, and perfectly suited for the parsing problem at hand!&lt;br /&gt;For parsing the email messages, I wrote functions to extract the subject, the sender-list, the body, etc, and these were inturn built using smaller functions. Bringing all these methods together, I was able to write complex working code in just a few hours. Testing and evaluating each function as I wrote it, part by part, building bigger ones from the smaller ones, and making sure that it worked at every step (oh its really peaceful when you're confident that what you've written so far works)&lt;br /&gt;&lt;br /&gt;Once these 2 major parts of the extension were written and tested, all I had to do was connect the dots. And yes, as you expect, it worked the first time. These little programming experience make me a better programmer, and that is the whole motivation behind these adventures, besides the fun ofcourse.&lt;br&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8968818456594497310-5694710153594364993?l=joelagnel.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://joelagnel.blogspot.com/feeds/5694710153594364993/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8968818456594497310&amp;postID=5694710153594364993' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/5694710153594364993'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/5694710153594364993'/><link rel='alternate' type='text/html' href='http://joelagnel.blogspot.com/2008/11/emacs-jabber-mail-notifier.html' title='my first emacs extension - A google mail notifier for Jabber'/><author><name>Joel Fernandes</name><uri>http://www.blogger.com/profile/04997674848378795829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8968818456594497310.post-8629942877588049099</id><published>2008-10-26T05:45:00.000-07:00</published><updated>2009-01-25T22:10:35.076-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='sql'/><title type='text'>A 3 level Nested SQL Query on a single table.</title><content type='html'>I had a lot of fun today writing the most complicated SQL query I've ever written.&lt;br /&gt;&lt;br /&gt;The table given to me was something like this:&lt;PRE&gt;  CUSTOMER          PRODUCT           SALE_DATE     STATE     QTY&lt;br /&gt;  -----------------------------------------------------------------&lt;br /&gt;  Bloom              Pepsi           1999-02-04      NY       2233&lt;br /&gt;  Bloom              Egg             1996-05-06      NJ       1233&lt;br /&gt;  Abhay              Pepsi           1987-06-07      NJ       2222&lt;br /&gt;  Bloom              Pepsi           1983-03-04      NJ       122&lt;br /&gt;&lt;/PRE&gt; Question:&lt;br /&gt;For each combination of customer and product, output the maximum&lt;br /&gt;and minimum sales quantities along with the corresponding dates&lt;br /&gt;(i.e., dates of those maximum and minimum sales quantities).&lt;br /&gt;--&lt;br /&gt;My first solution:&lt;br /&gt;Ah, I said, .. and wrote the following expression after scratching my head for a minute &lt;PRE&gt;SELECT MIN(QTY), MAX(QTY) FROM CUSTOMER_TABLE_NAME GROUP BY CUSTOMER, PRODUCT;&lt;/PRE&gt; But then.. reading the question carefully, I noticed that I had to give my result 2 dates, dates of those maximum and minimum sales quantities.&lt;br /&gt;&lt;br /&gt;So I scratched and scratched my head, and finally when I couldn't scratch any more, I wrote the following query, which is the most complicated I've ever written.. but it works very well and has rewarded me with a complete SQL refresher. The solution is below, I am using 3 levels of nesting with implicit inner joins, at various levels.&lt;br /&gt;&lt;b&gt;Final Solution:&lt;/b&gt;&lt;PRE&gt;SELECT min_table_2.customer, min_table_2.product, max_table_2.maxq2, min_table_2.minq2,&lt;br /&gt; max_table_2.sale_max, min_table_2.sale_min&lt;br /&gt;&lt;br /&gt; FROM (SELECT customer as c2, product as p2, sale_date as sale_min, min_table_1.minq as minq2&lt;br /&gt;     FROM  (SELECT customer as c1, product as p1, MIN(qty) as minq&lt;br /&gt;             FROM sales GROUP BY customer, product)min_table_1,&lt;br /&gt;             sales&lt;br /&gt;         WHERE  min_table_1.c1 = customer AND min_table_1.p1 = product AND min_table_1.minq = qty)min_table_2,&lt;br /&gt;&lt;br /&gt;     (SELECT customer as c2, product as p2, sale_date as sale_max, max_table_1.maxq as maxq2&lt;br /&gt;     FROM  (SELECT customer as c1, product as p1, MAX(qty) as maxq&lt;br /&gt;             FROM sales GROUP BY customer, product)max_table_1,&lt;br /&gt;             sales&lt;br /&gt;         WHERE  max_table_1.c1 = customer AND max_table_1.p1 = product AND max_table_1.maxq = qty)max_table_2&lt;br /&gt;&lt;br /&gt; WHERE min_table_2.c2 = max_table_2.c2 AND min_table_2.p2 = max_table_2.p2&lt;/PRE&gt;&lt;b&gt;Reasoning:&lt;/b&gt;&lt;br /&gt;The outer most FROM joins the inner 2 tables (that we generate).&lt;br /&gt;First we generate one result set from a subquery, the columns of this result set are: customer, product, MinQty.&lt;br /&gt;But, we need the date of the record with the minimum quantity, so we use write another subquery using the results of the inner most query, and generate a new result set with the following columns:   customer, product, MinQty, min_date&lt;br /&gt;We similarly generate another table for maximum quantity with columns: customer, product, maxQty, max_date.&lt;br /&gt;Once this much is done, we join these 2 generated result sets with the outer most query, the criteria for this implicit inner join is the customer and product columns of the minimum and maximum qty result sets should be equal. This is specified in our outer WHERE clause &lt;PRE&gt;WHERE min_table_2.c2 = max_table_2.c2 AND min_table_2.p2 = max_table_2.p2&lt;/PRE&gt; Once the outer level join is done, its just a matter of selecting the columns we need for the final result set.&lt;br /&gt;&lt;br /&gt;SQL queries can be real fun :)&lt;br /&gt;cheers!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8968818456594497310-8629942877588049099?l=joelagnel.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://joelagnel.blogspot.com/feeds/8629942877588049099/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8968818456594497310&amp;postID=8629942877588049099' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/8629942877588049099'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/8629942877588049099'/><link rel='alternate' type='text/html' href='http://joelagnel.blogspot.com/2008/10/3-level-nested-sql-query-most.html' title='A 3 level Nested SQL Query on a single table.'/><author><name>Joel Fernandes</name><uri>http://www.blogger.com/profile/04997674848378795829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8968818456594497310.post-9150396254054215531</id><published>2008-08-24T01:15:00.000-07:00</published><updated>2009-01-25T22:09:20.873-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ruby'/><category scheme='http://www.blogger.com/atom/ns#' term='rails'/><title type='text'>Ruby on Rails - Around filters</title><content type='html'>&lt;span style="font-size:100%;"&gt;In this article, I will show you how you can use RoR around filters, with exception handling to keep your controllers clean and do away with redundant chunks of code.&lt;br /&gt;&lt;br /&gt;The problem we're going to discuss is  writing repeated code in your controllers to perform validation on ActiveRecord objects (making sure they're non-nill most of the time), and then keep performing the same validation on all derivates of this non-nil object.&lt;br /&gt;And it does not end there, you have to perform the same validation in all actions that use the same active record object and its derivatives.&lt;br /&gt;&lt;br /&gt;To give you a better idea of what I'm talking about, here's a small snip  that suffers from the very same problem:&lt;br /&gt;&lt;br /&gt;Code from a BadPolicy controller:&lt;/span&gt;&lt;pre&gt;class BadPolicyController &lt; ActionController::Base&lt;br /&gt; def getpolicy&lt;br /&gt;  if user = User.find_by_name(params[:name])&lt;br /&gt;   if policy = user.policy&lt;br /&gt;    render :text =&gt; "Policy for user: #{policy.attributes}"&lt;br /&gt;   else&lt;br /&gt;    render :text =&gt; "Policy does not exist" # VALIDATION 1&lt;br /&gt;   end&lt;br /&gt;  else&lt;br /&gt;   render :text =&gt; "User doesn't exist"  # VALIDATION 2&lt;br /&gt;  end&lt;br /&gt; end&lt;br /&gt; def deletepolicy&lt;br /&gt;  if user = User.find_by_name(params[:name])&lt;br /&gt;   if policy = user.policy&lt;br /&gt;     policy.destroy&lt;br /&gt;     render :text =&gt; "Policy for deleted succesfully"&lt;br /&gt;   else&lt;br /&gt;    render :text =&gt; "Policy does not exist" # REPEATED&lt;br /&gt;   end&lt;br /&gt;  else&lt;br /&gt;   render :text =&gt; "User doesn't exist"  # REPEATED&lt;br /&gt;  end&lt;br /&gt; end&lt;br /&gt;end&lt;/pre&gt;&lt;span style="font-size:100%;"&gt;Eek! we're performing the same validations on a user, and on his policy (derived from a user object) twice, that's 4 validations in 2 actions, and the situations gets worse when we add more actions to the controller. 8 validations in 4 actions, 16 in 8 and so on!&lt;br /&gt;Patterns are a bad sign in programming, not only in aesthetic terms but in terms of hard-to-debug programs and increased development time.&lt;br /&gt;&lt;br /&gt;Here's what you could do, or rather should do:&lt;br /&gt;Before that, let me talk a bit about around filters which we'll be using to solve the above problem.&lt;br /&gt;Around filters allow us to define methods that wrap around every action that rails calls. So if I had an around filter for the above controller, I could control the execution of every action, execute code before calling the action, and after calling it, and also completely skip calling the action under certain circumstances if I wanted to.&lt;br /&gt;&lt;br /&gt;Here's an example of the around filter from the &lt;a href="http://api.rubyonrails.com/classes/ActionController/Filters/ClassMethods.html"&gt;Rails API documentation.&lt;/a&gt;&lt;/span&gt;&lt;br /&gt;&lt;pre&gt; around_filter :catch_exceptions&lt;br /&gt; private&lt;br /&gt;  def catch_exceptions&lt;br /&gt;   yield&lt;br /&gt; rescue =&gt; exception&lt;br /&gt;  logger.debug "Caught exception! #{exception}"&lt;br /&gt; raise&lt;br /&gt;end&lt;/pre&gt;&lt;span style="font-size:100%;"&gt;You can learn more about Around filters on the same page if you will, but my explanation here should suffice.&lt;br /&gt;&lt;br /&gt;Ok now lets get to work. In order to kill redundant validation code in every controller action, we will:&lt;br /&gt;(1) Wrap all the action invocations with our Around filter.&lt;br /&gt;(2) Define new methods in the model code that wrap auto-generated rails methods such as "policies" and "find_by_name".&lt;br /&gt;(3) Raise exceptions from within our newly created methods whenever required.&lt;br /&gt;(4) Catch these exceptions in our Around filter, and process them.&lt;br /&gt;&lt;br /&gt;First lets create a few custom exceptions that we'll be raising and catching:&lt;br /&gt;Create a new file in the lib with any meaningful name, mine's called 'exception.rb' and add the following code to it:&lt;br /&gt;&lt;/span&gt;&lt;pre&gt;# This our custom exception&lt;br /&gt;class InvalidDataEx &lt; RuntimeError&lt;br /&gt;end&lt;/pre&gt;&lt;span style="font-size:100%;"&gt;Now lets wrap a few auto-generated rails methods in the User model with our own.&lt;br /&gt;Code for the User model, is as below. Note that exceptions are raised wherever required.&lt;br /&gt;&lt;/span&gt;&lt;pre&gt;class User &lt; ActionController::Base&lt;br /&gt; def self.named(name)&lt;br /&gt;  find_by_name(name) or raise InvalidDataEx, "User doesn't exist"&lt;br /&gt; end&lt;br /&gt; def get_policy(name)&lt;br /&gt;  self.policy or raise InvalidDataEx, "Policy doesn't exist"&lt;br /&gt; end&lt;br /&gt;end&lt;/pre&gt;&lt;span style="font-size:100%;"&gt;Code for a Good policy Controller:&lt;br /&gt;&lt;/span&gt;&lt;pre&gt;class GoodPolicyController &lt; ActionController::Base&lt;br /&gt; def getpolicy&lt;br /&gt;  user = User.named(params[:name])&lt;br /&gt;  render :text =&gt; "Policy for user: #{user.get_policy.attributes}"&lt;br /&gt; end&lt;br /&gt; def getpolicy&lt;br /&gt;  user = User.named(params[:name])&lt;br /&gt;  user.get_policy.destroy&lt;br /&gt;  render :text =&gt;   "User policy deleted succesfully"&lt;br /&gt; end&lt;br /&gt;end&lt;/pre&gt;&lt;span style="font-size:100%;"&gt;Or even better, we can completely do away with the imperative programming style and write our actions in a functional style:&lt;br /&gt;&lt;/span&gt;&lt;pre&gt;class GoodPolicyController &lt; ActionController::Base&lt;br /&gt; def getpolicy&lt;br /&gt;  render :text =&gt; "Policy for user: #{User.named(params[:name]).get_policy.attributes}"&lt;br /&gt; end&lt;br /&gt; def deletepolicy&lt;br /&gt;  User.named(params[:name]).get_policy.destroy&lt;br /&gt;  render :text =&gt;   "User policy deleted succesfully"&lt;br /&gt; end&lt;br /&gt;end&lt;/pre&gt;&lt;span style="font-size:100%;"&gt;Imperative programs are about HOW things are done - "get user, validate user, get his policy, validate policy, render"&lt;br /&gt;Functional programs are about WHAT has to be done - "render a user's policy"&lt;br /&gt;&lt;br /&gt;Lovely !!  We've come a long way.&lt;br /&gt;&lt;br /&gt;Now lets wrap both the actions in our around filter:&lt;br /&gt;add the following to the controller class:&lt;br /&gt;&lt;/span&gt;&lt;pre&gt;around_filter :catch_exceptions&lt;br /&gt; private&lt;br /&gt; def catch_exceptions&lt;br /&gt;  yield&lt;br /&gt;  rescue InvalidDataEx =&gt; err&lt;br /&gt;  render :text =&gt; "#{err}"&lt;br /&gt;  logger.debug "Exception #{err} occurred."&lt;br /&gt; end&lt;/pre&gt;&lt;span style="font-size:100%;"&gt;Awesome! That's about it.&lt;br /&gt;&lt;br /&gt;What you should be left with after reading:&lt;br /&gt;Controller actions are expected to fetch data from models/lib, and render them, its not their job to perform data validation (most of the time).&lt;br /&gt;By centralizing logic, making sure that its in the right place, and reusing it whenever possible, developing complex applications can become fun, intuitive and easy. Also this style produces programs that have fewer bugs, are easier to maintain and that require lesser development time.&lt;br /&gt;&lt;br /&gt;When you see patterns in your code, then there's something wrong somewhere and a language as powerful and flexible as Ruby will leave you with options to identify and elliminate such patterns - as you saw in the example above.  All it takes is a bit of thought.&lt;br /&gt;&lt;br /&gt;Thanks for reading, comments are welcome!&lt;br /&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8968818456594497310-9150396254054215531?l=joelagnel.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://joelagnel.blogspot.com/feeds/9150396254054215531/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8968818456594497310&amp;postID=9150396254054215531' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/9150396254054215531'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/9150396254054215531'/><link rel='alternate' type='text/html' href='http://joelagnel.blogspot.com/2008/08/ruby-on-rails-around-filters-and.html' title='Ruby on Rails - Around filters'/><author><name>Joel Fernandes</name><uri>http://www.blogger.com/profile/04997674848378795829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8968818456594497310.post-7251355503220345023</id><published>2008-07-06T21:30:00.000-07:00</published><updated>2010-02-28T11:41:54.129-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ruby'/><category scheme='http://www.blogger.com/atom/ns#' term='rails'/><title type='text'>Metaprogramming keeps it neat: DSL creation techniques in Ruby - Part 1</title><content type='html'>&lt;span style=";font-family:verdana;font-size:100%;"  &gt;&lt;insert-for-i-suck-at-editing-a-blog&gt;Hi! &lt;/insert-for-i-suck-at-editing-a-blog&gt;&lt;/span&gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt;&lt;insert-for-i-suck-at-editing-a-blog&gt;Due to the lack of resources on building DSLs in Ruby on the internet, I've written a small guide of how you can use DSL creation techniques in Ruby to cut down on lot of redundant code, make it easier to maintain code and improve readability.  Hell you could eaven write your own language, here's your chance to discover how Rake, RoR and other amazing tools are written, and maybe even write one of your own!&lt;br /&gt;&lt;br /&gt;This is not a how-to steb-by-step guide on building a full fledged DSL, rather I will show you how you can apply DSL-implementation techniques to cut down on lots of redundant code by examples that get progressively more complex as we address problems or hit a dead-end.&lt;br /&gt;&lt;br /&gt;I've taken care to make sure that everything mentioned in this article makes sense even to novices, that's why I haven't slapped complicated code right way. Instead, I've taken a piecemeal approach.&lt;br /&gt;&lt;br /&gt;Rules of the game: Detecting when something is not right: When you see a lot of redundant code sitting around, somethings wrong somewhere. Why-TF should your rewrite pieces of code, when you can make the language do that for you! No I'm not talking about doing some functional programming. Relax, you'll find out soon enough.&lt;br /&gt;&lt;br /&gt;Redundancy sucks: If you've coded in languages like LISP, redundancy would be something just unacceptable to you. I actually haven't done much of Lisp, but a friend (lisp guy) managed to drill enough sense into me to stop typing that shit over and over again, and figure out alternatives!&lt;br /&gt;&lt;br /&gt;Learning how to apply K-I-S-S (keep it simple stupid).  While applying KISS, we tend to keep it so simple (KISS again) that the application turns out to be complex as it grows!  Not in terms of a single method or module, but the application as a whole: complexity in terms of debugging, maintaining etc. I'd buy 500 lines of moderately complex code any day over 1500 lines of simple stuff!&lt;br /&gt;&lt;br /&gt;DSLs to the rescue.  So what is a Domain specific language: Its a language that provides you with all the infrastructure, and functionality required to rapidly build applications for a specific domain, without worrying about the details.&lt;br /&gt;&lt;br /&gt;RoR - An amazing MVC framework that exploits ever corner of metaprogramming in Ruby and allows you to build simple yet powerful database driven web applications.&lt;br /&gt;&lt;br /&gt;Rake- a tool very similar to the unix make.  Rake (written completely in Ruby) executes "Rakefiles" allowing you to automate stuff like RoR migrations, file generation etc.&lt;br /&gt;&lt;br /&gt;Components of a DSL implementation:&lt;br /&gt;&lt;/insert-for-i-suck-at-editing-a-blog&gt;&lt;/span&gt;&lt;ul&gt;&lt;li&gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt; a base library providing you with all the functionality required for that domain (like ActiveRecord in RoR if you will)&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt; a domain specific instruction set, like:&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt;         "has_one", "has_many", "belongs_to" etc in Ruby On Rails&lt;br /&gt;"tasks", "desc", etc in Rake&lt;br /&gt;Now that you know what a DSL is. We're going to learn how its done in Ruby.&lt;br /&gt;&lt;br /&gt;Assuming your have a fair amount of Ruby knowledge, I'll walk you through some advanced concepts that we're going to use to spice up and make our app more intelligent so that it does all the hard work for us.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size:130%;"&gt;A few Ruby concepts&lt;/span&gt;&lt;br /&gt;&lt;/span&gt;&lt;ul&gt;&lt;li&gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt;Class vs Instance methods: Yea, I know you know this. But what I want to state here is classes themselves can contain code, independent of any method.  In RoR controllers, when you say "has_one", you're actually executing a class method "has_one", that takes the arguments and generates a whole bunch of instance methods for you.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt;&lt;pre&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;class Products&lt;br /&gt;has_many :vendors&lt;br /&gt;end&lt;/span&gt;&lt;br /&gt;&lt;/pre&gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt;The class method :has_many generates the instance method :vendors that returns an Active record collection of all the vendors for that particular product.&lt;/span&gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt;&lt;br /&gt;&lt;/span&gt;&lt;ul&gt;&lt;li&gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt;The define_method class method: define_method comes handy when you need to dynamically create an instance method in a class, all you have to it pass it the method name and block, and your instance method is up and ready.&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt;Example:&lt;br /&gt;&lt;pre&gt;&lt;span name="courier"&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;class Foo&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;  define_method :bar do&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;    puts "I'm from bar"&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;  end&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;end&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;is equivalent to:&lt;br /&gt;&lt;pre&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;class Foo&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;  def bar&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;    puts "I'm from bar"&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;  end&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;end&lt;/span&gt;&lt;/pre&gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt;Ok you're all set. With a basic knowledge of Ruby and the above concepts, you're ready to know what it takes to build a DSL in Ruby.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size:130%;"&gt;A Basic Implementation:&lt;/span&gt;&lt;br /&gt;Give me control over my method definitions!&lt;br /&gt;Inorder to cut down on code, the first thing I want to do is to get control over my methods, Every time a method is called, I want some code executed before and after it. Wow, is that even possible you say? Lets apply the concepts we learnt in the last section to make this possible:&lt;br /&gt;&lt;br /&gt;Instead of using "def" to defined methods, I'm going to create a keyword "defm" and give it some meaning. For this I'm going to create a class method defm and add some logic to it. Then I'm going to use defm to create my own methods, and control them!&lt;br /&gt;Here we go:&lt;br /&gt;&lt;pre&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;class MyClass&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt; def self.defm(method_name, &amp;amp;code)&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;   define_method method_name do&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;     puts "&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;starting style="color: rgb(0, 0, 153);"&gt;Starting method #{method_name}"&lt;/starting&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;     return_value = code.call&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;     puts "&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;method style="color: rgb(0, 0, 153);"&gt;method returned #{return_value}"&lt;/method&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;  end &lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt; end&lt;/span&gt;&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;span&gt;&lt;span&gt;&lt;span style="font-family:verdana;"&gt;&lt;span style="font-family:verdana;"&gt;&lt;span style="font-family:verdana;"&gt;&lt;pre&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;# Now lets use defm we just created:&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;   defm :foo  do&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;     puts "I'm inside foo!"&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;     true&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;   end&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;end&lt;/span&gt;&lt;/pre&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;x = MyClass.new&lt;br /&gt;x.foo&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;&lt;span style="font-style: italic;font-size:130%;" &gt;Output:&lt;br /&gt;Starting method foo&lt;br /&gt;I'm inside foo!&lt;br /&gt;method returned: true&lt;/span&gt;&lt;br /&gt;&lt;method&gt;&lt;/method&gt;&lt;/pre&gt;First I create a class method defm, then I define a method :foo using defm by passing in the method name as a symbol, and a block (body of the method). Executing foo on an instance gives us the desired result.&lt;br /&gt;&lt;br /&gt;Note that if the method definition of defm sitting in the Class itself is bothering, don't worry, we can always move it to a module. I'll show you how in the next section. Infact there are a whole bunch of methods coming up and we have to move it to the module, the class just defines methods using our newly created keywords, the implementation has to abstracted.&lt;br /&gt;&lt;br /&gt;Wow! I can now call methods created using our new defm keyword (in DSL terms), execute code before they start, and process their return value (boolean true in this case). You see where we're going? all the logic specific to defm-created methods can now be written in self.defm, and is not repeated with every method definition! Remarkable.&lt;br /&gt;&lt;br /&gt;Err.. not really.. there's a problem:&lt;br /&gt;&lt;br /&gt;What if I have a bar method, and try to call foo from it:&lt;br /&gt;&lt;pre  style="font-family:verdana;"&gt;&lt;span style="color: rgb(0, 0, 153);font-size:85%;" &gt;defm :bar  do&lt;/span&gt;&lt;span style="font-size:85%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:85%;" &gt; puts "I'm inside bar!"&lt;/span&gt;&lt;span style="font-size:85%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:85%;" &gt; foo&lt;/span&gt;&lt;span style="font-size:85%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:85%;" &gt; true&lt;/span&gt;&lt;span style="font-size:85%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:85%;" &gt;end&lt;/span&gt;&lt;/pre&gt;Trying to call x.bar throws the following error:&lt;br /&gt;NameError: undefined local variable or method `foo' for MyClass:Class&lt;br /&gt;&lt;br /&gt;Ruby complains because the block we're passing to defm is executing in the context of the Class in which we created it (so self = MyClass).&lt;br /&gt;&lt;br /&gt;Now what?&lt;br /&gt;&lt;br /&gt;That's where instance_eval comes in.&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt;instance_eval is required to change the context in which a block is executed. In the above example I'm passing a block to define_method. The block was created with self as the class object Bar. Inorder to execute the block with "self" as the instance of Bar on which it is called, all I need to do is use self.instance_eval(&amp;amp;block) instead of block.call .. the block now executes with self as the instance of Bar, not the object in which we created it.&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt;change:&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;return_value = code.call&lt;/span&gt;&lt;br /&gt;to:&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;  return_value = self.instance_eval(&amp;amp;code)&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;x.bar now gives:&lt;/span&gt;&lt;br /&gt;&lt;starting style="color: rgb(0, 0, 153);"&gt;&lt;/starting&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;I'm inside bar!&lt;/span&gt;&lt;br /&gt;&lt;starting style="color: rgb(0, 0, 153);"&gt;&lt;/starting&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;I'm inside foo!&lt;/span&gt;&lt;br /&gt;&lt;method style="color: rgb(0, 0, 153);"&gt;&lt;/method&gt;&lt;br /&gt;&lt;method&gt;&lt;/method&gt;Wow!&lt;br /&gt;Well done.. You now have built a basic working app by applying some metaprogramming but there are a few problems here:&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt;Problem 1:&lt;/span&gt;&lt;br /&gt;&lt;span style=";font-family:verdana;font-size:100%;"  &gt;If you look in terms of what is stored in memory, every method we define has the logic for&lt;br /&gt;"starting method" and "method returned" repeated. Though its not repeated in the code, it is repeated in every method definition stored in memory.&lt;br /&gt;&lt;br /&gt;This is what our "bar" and "foo" actually look like in memory as you might guess:&lt;br /&gt;&lt;pre&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;def bar&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;# code before method starts&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt; return_value = self.instance_eval(&amp;amp;code)&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;br /&gt;# code after method returns&lt;br /&gt;&lt;/span&gt;&lt;span style="color: rgb(0, 0, 153);font-size:130%;" &gt;end&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="font-size:130%;"&gt;&lt;span&gt;&lt;span&gt;&lt;span style="font-family:verdana;"&gt;&lt;span style="font-family:verdana;"&gt;&lt;span style="font-family:verdana;"&gt;&lt;pre&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;def foo&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;# code before method starts&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt; return_value = self.instance_eval(&amp;amp;code)&lt;/span&gt;&lt;br /&gt;# code after method returns&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;end&lt;/span&gt;&lt;br /&gt;&lt;/pre&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/pre&gt;Ugh! That's redundant again! (though thankfully only in memory this time) -we'll fix this soon enough.&lt;br /&gt;&lt;br /&gt;Problem 2:&lt;br /&gt;What we're passing to defm is a ruby block. Blocks or Procs aren't really methods, they're a lot different.  Trying to return a value in the middle using the return keyword will break it.&lt;br /&gt;&lt;br /&gt;Try this:&lt;br /&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;&gt; func = lambda { |x|&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;*   return 1&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;&gt; }&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;&gt; self.instance_eval(&amp;amp;func)&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;LocalJumpError: unexpected return&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;    from (irb):97&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;    from (irb):99:in `instance_eval'&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;    from (irb):99&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Problem 3:&lt;br /&gt;We also haven't talked about passing arguments to our newly created methods. Even if we did, methods created using "define_method" start to execute even when passed the wrong no. of arguments.  Our current implementation isn't smart enough to catch this.&lt;br /&gt;&lt;br /&gt;Try this, it will still work:&lt;br /&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;&gt; class Object&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;&gt; define_method :x do&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;*  |x|&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;*  puts x&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;&gt;  end&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;&gt; end&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;=&gt; #&lt;/span&gt;&lt;proc:0xb7a11a28@(irb):56 style="color: rgb(0, 0, 153);"&gt;&lt;/proc:0xb7a11a28@(irb):56&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;&gt; x&lt;/span&gt;&lt;br /&gt;&lt;span style="color: rgb(0, 0, 153);"&gt;(irb):57: warning: multiple values for a block parameter (0 for 1)&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Ruby only warns you, it doesn't raise an ArgumentError as it normally would with a real method. Blocks unlike real methods in ruby can be passed the wrong no.of arguments, this means our methods aren't as robust as real ones.&lt;br /&gt;&lt;br /&gt;In the next part (which is coming soon), we're going to address all these issues. We'll also build a smarter defm implementation in a Rails controller to demonstrate how we used this technique to cut down on tonnes of redundant code.&lt;br /&gt;&lt;br /&gt;Hope you enjoyed this so far, stay tuned for some more fun!&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/8968818456594497310-7251355503220345023?l=joelagnel.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://joelagnel.blogspot.com/feeds/7251355503220345023/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=8968818456594497310&amp;postID=7251355503220345023' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/7251355503220345023'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8968818456594497310/posts/default/7251355503220345023'/><link rel='alternate' type='text/html' href='http://joelagnel.blogspot.com/2008/07/redundancy-kills-excercise-in.html' title='Metaprogramming keeps it neat: DSL creation techniques in Ruby - Part 1'/><author><name>Joel Fernandes</name><uri>http://www.blogger.com/profile/04997674848378795829</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry></feed>
