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

<channel>
	<title>Metaphysical Developer</title>
	<atom:link href="http://metaphysicaldeveloper.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://metaphysicaldeveloper.wordpress.com</link>
	<description>Thoughts on Software Development</description>
	<lastBuildDate>Fri, 06 Jan 2012 12:23:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='metaphysicaldeveloper.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Metaphysical Developer</title>
		<link>http://metaphysicaldeveloper.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://metaphysicaldeveloper.wordpress.com/osd.xml" title="Metaphysical Developer" />
	<atom:link rel='hub' href='http://metaphysicaldeveloper.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Implementing Minecraft in WebGL</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2011/12/20/implementing-minecraft-in-webgl/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2011/12/20/implementing-minecraft-in-webgl/#comments</comments>
		<pubDate>Tue, 20 Dec 2011 12:17:22 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[hacking]]></category>
		<category><![CDATA[Minecraft]]></category>
		<category><![CDATA[computational geometry]]></category>
		<category><![CDATA[hacker news]]></category>
		<category><![CDATA[team fortress 2]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=447</guid>
		<description><![CDATA[TL;DR: Source here, live demo here. WebGL is an amazing piece of technology that enables browsers to natively render hardware accelerated 3d creations (yay, no o3d plugin needed!). I&#8217;ve always been specially amazed by what Mr Doob has been doing with his Three.js framework for quite a while (in particular his participation on the ROME project, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=447&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>TL;DR: Source <a href="https://github.com/danielribeiro/WebGLCraft">here</a>, live demo <a href="http://danielribeiro.github.com/WebGLCraft/">here</a>.</p>
<div id="attachment_462" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.ro.me/" target="_blank"><img class=" wp-image-462    " title="ROME project" src="http://metaphysicaldeveloper.files.wordpress.com/2011/12/romeair.jpg?w=300&#038;h=130" alt="ROME project" width="300" height="130" /></a><p class="wp-caption-text">ROME project</p></div>
<p><a href="http://learningwebgl.com/blog/?page_id=1217">WebGL</a> is an amazing piece of technology that enables browsers to natively render hardware accelerated 3d creations (yay, no <a href="http://code.google.com/p/o3d/">o3d plugin</a> needed!). I&#8217;ve always been specially amazed by what <a href="http://mrdoob.com/">Mr Doob</a> has been doing with his <a href="https://github.com/mrdoob/three.js/">Three.js</a> framework for quite a while (in particular his participation on the <a href="http://www.ro.me/">ROME</a> project, which <a title="ClojureScript vs Coffeescript" href="http://metaphysicaldeveloper.wordpress.com/2011/08/28/clojurescript-vs-coffeescript/">I briefly talked about recently</a>). Nonetheless, there are some other amazing WebGL creations around, such as those featured on <a href="http://www.chromeexperiments.com/">Chrome Experiments</a>, those crafted by <a href="http://oos.moxiecode.com/blog/experiments/javascript-webgl/">OOS</a> and the projects recently presented on <a href="http://blog.thejit.org/2011/12/09/webglcamp/">WebGLCamp</a> (not to mention the amazing <a href="http://blog.tojicode.com/2011/10/source-engine-levels-in-webgl-video.html">Team Fortress 2</a> level vizualizer).</p>
<p>One thing that has bothered me though, throughout all the examples, is the lack of interactivity (one glaring exception was <a href="http://www.glge.org/">GLGE</a>&#8216;s <a href="http://www.glge.org/vehicle-physics-in-webgl-using-glge-and-jiglibjs/">car demo</a>) .</p>
<span style="text-align:center; display: block;"><a href="http://metaphysicaldeveloper.wordpress.com/2011/12/20/implementing-minecraft-in-webgl/"><img src="http://img.youtube.com/vi/r_gIAjVD4Dc/2.jpg" alt="" /></a></span>
<p>This seemed to be from the fact the 3d collision is quite a bit more involved than 2d (MIT&#8217;s lecture <a href="http://ocw.mit.edu/courses/mechanical-engineering/2-158j-computational-geometry-spring-2003/lecture-notes/lecnotes10.pdf">notes on Computational Geometry</a>, and even on Doom 3&#8242;s recently released <a href="https://github.com/TTimo/doom3.gpl/blob/master/neo/game/physics/Physics_RigidBody.cpp">source code</a>, can give you an idea of how much involved it can get). And since <a href="http://www.smashinglabs.pl/what-do-we-need-for-html5-games-to-be-awesome">this is considered</a> to be one of the important things  that 3d games need, I was not happy with my hands off <a href="http://news.ycombinator.com/item?id=3037014">answer of this topic</a> on Hacker News. Thus I took the challenge of making a a 3d game in WebGL with collision detection.</p>
<p>Implementing Minecraft Classic (which is <a href="http://www.minecraft.net/classic/play">playable online</a> for free) seemed like a good candidate for such project, as its mechanics are simple, and yet meaningful (not to mention that I am <a title="Hacking a Gnuplot into Minecraft" href="http://metaphysicaldeveloper.wordpress.com/2011/07/31/hacking-a-gnuplot-into-minecraft/">big fan</a> of Notch&#8217;s creation). If you don&#8217;t know anything about Minecraft, I wrote a small <a title="Hacking a Gnuplot into Minecraft" href="http://metaphysicaldeveloper.wordpress.com/2011/07/31/hacking-a-gnuplot-into-minecraft/">intro</a> about it a few months ago.</p>
<div class="mceTemp mceIEcenter">
<div id="attachment_471" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.youtube.com/watch?v=kn2-d5a3r94" target="_blank"><img class="size-medium wp-image-471 " title="minecraftenterprise" src="http://metaphysicaldeveloper.files.wordpress.com/2011/12/minecraftenterprise1.jpg?w=300&#038;h=168" alt="Enterprise created in Minecraft" width="300" height="168" /></a><p class="wp-caption-text">Enterprise created in Minecraft</p></div>
</div>
<p>Three.js was selected as the rendering lib not only because I really like Mr Doob&#8217;s work, but also because it has is quite mature, is open source, has lots of examples and provides a very <a href="http://mrdoob.github.com/three.js/examples/webgl_geometry_minecraft_ao.html">promising starting point</a>: a visualization of a Minecraft world, which includes a <a href="http://mrdoob.github.com/three.js/examples/js/ImprovedNoise.js">noise function</a> for generating it.</p>
<p style="text-align:center;"><a href="http://mrdoob.github.com/three.js/examples/webgl_geometry_minecraft_ao.html" target="_blank"><img class="aligncenter" src="https://a248.e.akamai.net/assets.github.com/img/874ff84a3eba2a41d57d9edbbd3badb6a5f2ece2/687474703a2f2f6d72646f6f622e6769746875622e636f6d2f74687265652e6a732f6173736574732f6578616d706c65732f32395f67656f6d657472795f6d696e6563726166742e706e67" alt="" width="200" height="150" /></a></p>
<p>So all that was left was <em>just</em> adding Collision Detection. Well&#8230; this is where things started getting interesting.</p>
<h2>Minecraft Collision Detection Attempt 1: JigLibJS</h2>
<p><a href="http://www.jiglibjs.org/">Jiglibjs</a> is a port of <a href="http://www.jiglibflash.com/blog/">Jiglibflash</a>, which in itself is a port of <a href="http://www.rowlhouse.co.uk/jiglib/">Jiglib</a> for c++. It seemed pretty promising, since there was <a href="http://timothypoon.com/blog/2011/03/08/using-three-js-and-jiglibjs-together/">some people</a> using it (along with three.js), and I had <a title="ClojureScript vs Coffeescript" href="http://metaphysicaldeveloper.wordpress.com/2011/08/28/clojurescript-vs-coffeescript/">great success</a> with using physics libs in the past for 2d games, so it seemed like a natural choice.</p>
<p>After getting it to work with a prototype of the game, it became clear that some things were very wrong. The amazing demos were too simple for Minecraft, and the rotation would get really wrong when walking on simple plane surfaces (something I speculate happening due to some <a href="http://en.wikipedia.org/wiki/Numerical_stability">numerical stability</a> differences from ActionScript and Javascript, alongside with some AS3-&gt; Flash compiler bugs).</p>
<div id="attachment_484" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.jiglibjs.org/demos_official/collisions_similar.htm" target="_blank"><img class="size-medium wp-image-484 " title="Screen Shot 2011-12-19 at 11.32.35 PM" src="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-19-at-11-32-35-pm.png?w=300&#038;h=133" alt="" width="300" height="133" /></a><p class="wp-caption-text">JigLibJS demo</p></div>
<p>After some fun 4 dimension <a href="https://github.com/danielribeiro/WebGLCraft/commit/eb78fbb0a8d2cdaeffefeb5868d65c3cd76f6087#L0L8">matrix hacking</a>, and failing to get around the bugs, I was ready to move on. Thankfully I found another port of JigLibJS which seemed to correct such issues&#8230;</p>
<h2>Minecraft Collision Detection Attempt 2: JigLibJS2</h2>
<p>The fact that someone tried to make a more complex example on JigLibJS, failed, but was tenacious enough to write its own AS3 -&gt; JS compiler to make another port (which worked!) made a very positive impression.</p>
<div class="wp-caption aligncenter" style="width: 352px"><a href="http://www.brokstuk.com/jiglibjs2/" target="_blank"><img class=" " src="http://www.brokstuk.com/jiglibjs2/screenshot.png" alt="" width="342" height="269" /></a><p class="wp-caption-text">JigLibJS2 Vehicle Physics Demo</p></div>
<p>It was also very positive the fact that the interface was almost the same to JigLibJS, making the change to the existing code very small. The problems started to come when trying to make the player cube jump: the cube would not always collide with the bottom plane. This was solved by making <a href="https://github.com/danielribeiro/WebGLCraft/blob/021a83783d6c6ddce86141d76b828a34402f3903/lib/coffee/minecraft.coffee#L201">more collision iterations</a>. Soon enough another problem came up: when trying to move inside an adjacent static cube (even when both the player and the cube were in the same height), sometimes the player would get a rotation. Trying to set it to no rotation every iteration did not actually help, as the player would still sometimes get a vertical velocity when trying to penetrate the block.</p>
<p>Still, rolling my own Physics Engine seemed a bit daunting, and I decided to try out another lib:</p>
<h2>Minecraft Collision Detection Attempt 3:  Ammo.js</h2>
<p><a href="http://granular.cs.umu.se/browserphysics/?p=349">Ammo.js</a> is a port of the C++ physics engine <a href="http://bulletphysics.org/wordpress/">BulletPhysics</a>, that runs on top of the <a href="http://llvm.org/">LLVM</a>&#8216;s Javascript port, aka <a href="https://github.com/kripken/emscripten">Emscripten</a>. Everything looked amazing this time: the <a href="http://granular.cs.umu.se/ammo/Demos/index.html">demos</a> not only looked great, but were very hackable, and had no problems that I previously had.</p>
<div class="wp-caption aligncenter" style="width: 251px"><a href="http://granular.cs.umu.se/ammo/Demos/BoxDemo/index.html" target="_blank"><img src="http://granular.cs.umu.se/ammo/Demos/BoxDemo/thumb.png" alt="" width="241" height="241" /></a><p class="wp-caption-text">Ammo.js Demo</p></div>
<p>But then it came the time to try to get to more Minecrafty world dimensions. It was a bit disappointing when mere 400 cubes made the physics engine go to a crawl (even when using static cubes). It became clear that I needed O(1) collision algorithms, which is very doable for Minecraft Classic, as only the player can move, and there is always a constant amount of cubes the player can collide with at any given time. And now there were no more libs left to evaluate.</p>
<h2>Minecraft Collision Detection Attempt 4:  Rays!</h2>
<p><a href="https://github.com/mrdoob/three.js/issues/424">Rays</a> are the standard way of detecting line/Object collision in Three.js. A very simple interactive <a href="http://oos.moxiecode.com/js_webgl/ray_collision/index.html">demo</a> by OOS seemed like it could do the trick. It had the advantage of being very simple, and constant time (given that I selected the possible blocks to collide with, as the traditional <a href="https://github.com/mrdoob/three.js/blob/master/src/core/Ray.js#L16">Ray.intersectObjects</a> actually tries to intersect all objects on the Scene).</p>
<div id="attachment_491" class="wp-caption aligncenter" style="width: 310px"><a href="http://oos.moxiecode.com/js_webgl/ray_collision/index.html"><img class="size-medium wp-image-491" title="Screen Shot 2011-12-20 at 1.27.12 AM" src="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-20-at-1-27-12-am1.png?w=300&#038;h=157" alt="" width="300" height="157" /></a><p class="wp-caption-text">Ray Collision Demo</p></div>
<p>The OOS example had some issues (like trapping the player cube when jumping up and down, while hodling the forward key). This was solvable by using 12 rays correspoding to the edges of the cube that represented the player. Actually, this did not help all the time, as some rays would not collide with the world blocks if the ray&#8217;s origin inside a blocks&#8217;s face. This is a <a href="https://github.com/mrdoob/three.js/issues/759#issuecomment-2743974">bug</a> yet to be solved, but I got around it by using 24 rays (two directions for every edge of the player cube).</p>
<p>Things were going well enough that I finally moved into adding textures to the game. However, after making the player cuboid have size dimensions to Minecraft&#8217;s, instead of having the same size of the world&#8217;s cube (which was what I was experimenting with so far), I noticed that the ray would give false positives depending on the height position of the cube. This only happened when the numbers were all too exact, instead of with minor deltas, as you&#8217;d expect from using rays cast from the mouse pointer (as it is <a href="http://mrdoob.github.com/three.js/examples/canvas_interactive_cubes.html">usually</a> used on Three.js&#8217; demos).</p>
<p>This, and the fact that collision was taking about half the time of every tick (which was constant, due the improved collision algorithm) made me move on to&#8230;</p>
<h2>Minecraft Collision Detection Attempt 5: Cube Projection</h2>
<p>Up until now I had hopes that I would be able to eventually rotate the player <a href="http://en.wikipedia.org/wiki/Cuboid">cuboid</a> according to its camera. After having so many troubles with so many collision systems, I simplified the problem: collision of unrotated cuboids. This is a really simple problem: from the <a href="http://en.wikipedia.org/wiki/Separating_axis_theorem">Separating Plane Theorem</a>, it is easy to see that  I only need to see if the orthogonal projections of the cuboids, which, from the <a href="http://en.wikipedia.org/wiki/Separating_axis_theorem">Separating Axis Theorem</a>, means I only need to check out if the unrotated rectangles from the projected faces collide, which finally means I only need to check if the projected intervals collide. All of this amounts to <a href="https://github.com/danielribeiro/WebGLCraft/blob/master/lib/collision.coffee">18 lines of Coffeescript</a>:</p>
<p><pre class="brush: ruby; wrap-lines: false;">
CollisionUtils =
    # The two intervals are [s1, f1] and [s2, f2]
    testIntervalCollision: (s1, f1, s2, f2) -&gt;
        return true if s1 == s2
        return f1 &gt;= s2 if s1 &lt; s2         return f2 &gt;= s1

    #Cubes are objects with vmax, vmin (the vertices with greatest/smallest values)
    #properties. Assumes unrotated cubes.
    testCubeCollision: (cube1, cube2) -&gt;
        fcol = CollisionUtils.testIntervalCollision
        for axis in ['x', 'y', 'z']
            collides = fcol cube1.vmin[axis], cube1.vmax[axis]
            , cube2.vmin[axis], cube2.vmax[axis]
            return false unless collides
        return true

window.CollisionUtils = CollisionUtils
</pre></p>
<p>Which in retrospect is what I should have tried in the first place. At least I learned some stuff in the process.</p>
<h1>Not quite finished yet: Camera</h1>
<p><a href="http://paulirish.com/">Paul Irish</a> did a pretty amazing job with the Three.js <a href="https://github.com/mrdoob/three.js/blob/f32962f393dc3dd47f9dffaafe5899ca05c5e5ea/src/extras/controls/FirstPersonControls.js">FirstPersonControls.js</a>, which is the one that powers the Three.js Minecraft visualizer. The problem with this camera is that it makes hard to actually play Minecraft, as its default mode is to be always moving, making hard to place/remove blocks. Real Minecraft uses first person shooter camera which cannot be achieved with current browsers, as there is no <a href="https://www.w3.org/Bugs/Public/show_bug.cgi?id=9557">way to trap</a> the user&#8217;s mouse. Nevertheless, Minecraft on Android uses a touch and drag camera that can easily be implemented in JS. This camera works they same way as the one on <a href="http://blog.tojicode.com/">Brandon</a> Jones&#8217; <a href="http://media.tojicode.com/q3touch/">Quake 3 WebGL</a> implementation.</p>
<div id="attachment_498" class="wp-caption aligncenter" style="width: 310px"><a href="http://media.tojicode.com/q3touch/" target="_blank"><img class="size-medium wp-image-498 " title="Screen Shot 2011-12-20 at 12.49.07 AM" src="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-20-at-12-49-07-am.png?w=300&#038;h=168" alt="" width="300" height="168" /></a><p class="wp-caption-text">Quake 3 demo</p></div>
<p>Therefore I refactored, and <a href="http://js2coffee.org/">converted</a> to Coffeescript, the FirstPersonControls to work as a click and drag camera. The resulting 86 lines of code can be seen <a href="https://github.com/danielribeiro/WebGLCraft/blob/master/lib/camera.coffee">here</a>.</p>
<h1>Adding/Removing Blocks</h1>
<p>This is where Rays worked really well. In fact, Mr. Doob even have a <a href="http://mrdoob.com/projects/voxels/">voxel</a> editor example which shows really well how to make an app that adds/removes cubes on a 3d grid:</p>
<div class="wp-caption aligncenter" style="width: 210px"><a href="http://mrdoob.com/projects/voxels/" target="_blank"><img class=" " src="https://a248.e.akamai.net/assets.github.com/img/84fdcdb2c933be06c992850c6bb5da0a31efebbf/687474703a2f2f6d72646f6f622e6769746875622e636f6d2f74687265652e6a732f6173736574732f70726f6a656374732f31305f766f78656c732e706e67" alt="" width="200" height="150" /></a><p class="wp-caption-text">WebGL Voxel Editor</p></div>
<p>The only issue I&#8217;ve found was that my floor plane was too big, which messed up the Ray/plane collision in certain angles. So I coded this intersection directly:</p>
<p><pre class="brush: ruby; wrap-lines: false;">
    getCubeOnFloorPosition: (ray) -&gt;
        return null if ray.direction.y &gt;= 0
        ret = vec()
        o = ray.origin
        v = ray.direction
        t = (-o.y) / v.y
        ret.y = 0
        ret.x = o.x + t * v.x
        ret.z = o.z + t * v.z
        return @addHalfCube ret
</pre></p>
<div id="LC395">
<h1>Conclusions</h1>
<p>I felt the result was quite satifying (the live <a href="http://danielribeiro.github.com/WebGLCraft/">demo</a>, and the <a href="https://github.com/danielribeiro/WebGLCraft">MIT licensed source</a>, can both be found on Github):</p>
<div style="display:inline-block;margin-right:5px;">
<div id="attachment_502" class="wp-caption alignnone" style="width: 250px"><a href="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-17-at-3-00-58-am.png"><img class=" wp-image-502 " title="Screen Shot 2011-12-17 at 3.00.58 AM" src="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-17-at-3-00-58-am.png?w=240&#038;h=146" alt="" width="240" height="146" /></a><p class="wp-caption-text">Minecraft Brick Pyramid</p></div>
</div>
<div style="display:inline-block;">
<div id="attachment_504" class="wp-caption alignright" style="width: 250px"><a href="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-17-at-6-44-36-pm.png"><img class=" wp-image-504 " title="Screen Shot 2011-12-17 at 6.44.36 PM" src="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-17-at-6-44-36-pm.png?w=240&#038;h=130" alt="" width="240" height="130" /></a><p class="wp-caption-text">WebGL Brick Pyramid</p></div>
</div>
</div>
<p>Granted, it starts skipping frames quite often as you add more blocks. The original example from Dr. Doob&#8217;s  didn&#8217;t because he created a single Mesh (aka object scene) composed of all blocks. Doing such would make adding/removing blocks a lot more involved (or force me to handle some area loading/unloading), which is a project in itself. Note that the rendering, and not the collision system, is the real bottleneck at this point.</p>
<p>All of this made me admire Notch&#8217;s work on Minecraft a lot more, as Minecraft <a href="http://www.minecraftwiki.net/wiki/Chunks">can handle over</a> 21&#215;21 loaded chunks of 16x16x128 (over 14 million blocks!) in any given time. The Three.js community had some <a href="https://github.com/mrdoob/three.js/issues/720#issuecomment-2613570">great insights</a> on how to achieve such performance over WebGL, which requires the use of <a href="http://en.wikipedia.org/wiki/Shader">shaders</a>, which are quite low level (even if you use the respective <a href="http://code.google.com/p/threedlibrary/">TDL Google Library</a> for this, or <a href="http://www.haskell.org/haskellwiki/GPipe">GPipe</a> to write the shaders in Haskell), and would probably require a lot of collision code to be also written in also a very low level language (slash GPipe&#8217;s Haskell). I found it also interesting that shaders can be used in <a href="http://granular.cs.umu.se/browserphysics/?p=237">some clever ways</a> to improve JS performance.</p>
<p>And finally, it is important to note that a lot of very people a lot smarter than me have been doing <a href="http://www.khronos.org/webgl/wiki/User_Contributions">some great work</a> to make working with WebGL and making 3d games much simpler.</p>
<p>There are also other renderer libraries besides Three.js: <a href="http://scenejs.org/">Scene.js</a>, <a href="http://senchalabs.github.com/philogl/">PhiloGL</a>, <a href="http://aerotwist.com/a3/">A3</a> (recently presented on the <a href="http://blog.thejit.org/2011/12/09/webglcamp/">WebGL Camp</a>), <a href="http://www.ambiera.com/coppercube/">Coppercube</a> (which is not open source, but can use flash for 3d rendering as well) and <a href="http://www.glge.org/">GLGE</a>.</p>
<p><em><a href="http://news.ycombinator.com/item?id=3376620"><img title="hacker news" src="http://1.gravatar.com/blavatar/96c849b03aefaf7ef9d30158754f0019?s=20" alt="" width="20" height="20" />Hacker News Comments</a></em></p>
<br /> Tagged: <a href='http://metaphysicaldeveloper.wordpress.com/tag/computational-geometry/'>computational geometry</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/hacker-news/'>hacker news</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/team-fortress-2/'>team fortress 2</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/447/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/447/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/metaphysicaldeveloper.wordpress.com/447/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/metaphysicaldeveloper.wordpress.com/447/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/metaphysicaldeveloper.wordpress.com/447/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/metaphysicaldeveloper.wordpress.com/447/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/metaphysicaldeveloper.wordpress.com/447/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/metaphysicaldeveloper.wordpress.com/447/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/metaphysicaldeveloper.wordpress.com/447/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/metaphysicaldeveloper.wordpress.com/447/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/metaphysicaldeveloper.wordpress.com/447/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/metaphysicaldeveloper.wordpress.com/447/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/metaphysicaldeveloper.wordpress.com/447/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/metaphysicaldeveloper.wordpress.com/447/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=447&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2011/12/20/implementing-minecraft-in-webgl/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/12/romeair.jpg?w=300" medium="image">
			<media:title type="html">ROME project</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/12/minecraftenterprise1.jpg?w=300" medium="image">
			<media:title type="html">minecraftenterprise</media:title>
		</media:content>

		<media:content url="https://a248.e.akamai.net/assets.github.com/img/874ff84a3eba2a41d57d9edbbd3badb6a5f2ece2/687474703a2f2f6d72646f6f622e6769746875622e636f6d2f74687265652e6a732f6173736574732f6578616d706c65732f32395f67656f6d657472795f6d696e6563726166742e706e67" medium="image" />

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-19-at-11-32-35-pm.png?w=300" medium="image">
			<media:title type="html">Screen Shot 2011-12-19 at 11.32.35 PM</media:title>
		</media:content>

		<media:content url="http://www.brokstuk.com/jiglibjs2/screenshot.png" medium="image" />

		<media:content url="http://granular.cs.umu.se/ammo/Demos/BoxDemo/thumb.png" medium="image" />

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-20-at-1-27-12-am1.png?w=300" medium="image">
			<media:title type="html">Screen Shot 2011-12-20 at 1.27.12 AM</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-20-at-12-49-07-am.png?w=300" medium="image">
			<media:title type="html">Screen Shot 2011-12-20 at 12.49.07 AM</media:title>
		</media:content>

		<media:content url="https://a248.e.akamai.net/assets.github.com/img/84fdcdb2c933be06c992850c6bb5da0a31efebbf/687474703a2f2f6d72646f6f622e6769746875622e636f6d2f74687265652e6a732f6173736574732f70726f6a656374732f31305f766f78656c732e706e67" medium="image" />

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-17-at-3-00-58-am.png?w=300" medium="image">
			<media:title type="html">Screen Shot 2011-12-17 at 3.00.58 AM</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-17-at-6-44-36-pm.png?w=300" medium="image">
			<media:title type="html">Screen Shot 2011-12-17 at 6.44.36 PM</media:title>
		</media:content>

		<media:content url="http://1.gravatar.com/blavatar/96c849b03aefaf7ef9d30158754f0019?s=20" medium="image">
			<media:title type="html">hacker news</media:title>
		</media:content>
	</item>
		<item>
		<title>ClojureScript vs Coffeescript</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2011/08/28/clojurescript-vs-coffeescript/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2011/08/28/clojurescript-vs-coffeescript/#comments</comments>
		<pubDate>Sun, 28 Aug 2011 20:16:48 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[hacking]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[coffeescript]]></category>
		<category><![CDATA[html5]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=420</guid>
		<description><![CDATA[A language that doesn&#8217;t affect the way you think about programming, is not worth knowing &#8211; Alan J. Perlis In the past few years Javascript has gained a lot of attention and ubiquity: HTML5 technologies leverage a lot of Javascript, which enables people to create amazing dream worlds (like the in the ROME project) with [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=420&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="padding-left:30px;"><em>A language that doesn&#8217;t affect the way you think about programming, is not worth knowing </em></p>
<p style="padding-left:30px;">&#8211; <a href="http://www-pu.informatik.uni-tuebingen.de/users/klaeren/epigrams.html">Alan J. Perlis</a></p>
<p>In the past few years Javascript has gained a lot of attention and ubiquity: HTML5 technologies leverage a lot of Javascript, which enables people to create amazing <a href="http://googlecode.blogspot.com/2011/05/dreams-in-3d-webgl-experience-for.html">dream worlds</a> (like the in the <a href="http://www.ro.me/tech/">ROME</a> project) with WebGL, V8 brings a lot of <a href="http://en.wikipedia.org/wiki/Just-in-time_compilation">JIT</a> techniques to a JavaScript Virtual Machine which helps Google Chrome be a very fast browser, and powers <a href="http://nodejs.org/">NodeJS</a> (allowing people to create a web page in a single programming language).</p>
<p style="text-align:center;"><a href="http://www.ro.me/" target="_blank"><img class="aligncenter size-full wp-image-429" title="Rome project" src="http://metaphysicaldeveloper.files.wordpress.com/2011/08/rome.png?w=490&#038;h=277" alt="" width="490" height="277" /></a></p>
<p>Javascript also powers queries in NoSQL databases like <a href="http://www.mongodb.org/display/DOCS/MapReduce#MapReduce-Overview">Mongo</a> and <a href="http://couchdb.apache.org/">CouchDB</a>, and it can be used when making <a href="http://doc.qt.nokia.com/4.7-snapshot/qdeclarativejavascript.html">QT</a> applications, 3d Games in <a href="http://www.unity-tutorials.com/forum/viewtopic.php?p=108">Unity</a> and even mobile apps with frameworks like <a href="http://www.webmynd.com/html5/">WebMynd</a> and <a href="http://www.phonegap.com/">PhoneGap</a>. It has been a long way from the old days when it was confined to the browser, and mostly used for form validation.</p>
<p>In spite of all of this attention, Javascript has been so misunderstood that attention to its <a href="http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742">Good Parts</a> had to drawn. It doesn&#8217;t help that its prototype based OO was first introduced by the rather unknown language <a href="http://en.wikipedia.org/wiki/Self_%28programming_language%29">Self</a>, despite the several advantages it has when compared to traditional class based OO (the paper <a href="http://labs.oracle.com/self/papers/organizing-programs.html"><em>Organizing Programs Without Classes</em></a>, written by Google&#8217;s Senior VP of Operations <a href="http://research.google.com/pubs/author79.html">Urs Hölzle</a>, who, among other things, also contributed to key JIT techniques like <a href="http://en.wikipedia.org/wiki/Inline_caching#cite_note-HCU-1">polymorphic inline caching</a>).</p>
<p>Therefore it is not surprising that there are <a href="https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS">many projects that</a> compile existing languages to Javascript. Many of these were too focused on the web platform (like <a href="http://code.google.com/webtoolkit/">Google Web Toolkit</a> and the amazing <a href="http://cappuccino.org/">Cappuccino</a>&#8216;s Objective-j). On more recent years languages are targeting the whole JS ecosystem (which makes a very poignant argument that <a href="http://www.hanselman.com/blog/JavaScriptIsAssemblyLanguageForTheWebPart2MadnessOrJustInsanity.aspx"><em>JavaScript is Assembly Language for the Web</em></a>). <a href="http://jashkenas.github.com/coffee-script/">Coffeescript</a> is one of such languages, which very fond (I&#8217;ve  <a href="http://metaphysicaldeveloper.wordpress.com/2011/03/31/354/">written</a> about it recently).</p>
<p>About a month ago <a href="https://github.com/clojure/clojurescript">ClojureScript</a> was <a href="http://clojure.com/blog/2011/07/22/introducing-clojurescript.html">released</a>, porting the <a href="http://clojure.org/">Clojure</a> language from Java ecosystem to the JS. Clojure is quite an amazing effort of engineering, not only for being a very successful Lisp on the JVM, but also for its novel approach of handling time and state (which its creator, Rich Hickey, <a href="http://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey">explains</a> really well).</p>
<p>I was really excited to see the examples, but I was a bit bummed out that the most interesting example was a <a href="http://pragprog.com/magazines/2011-08/hello-clojurescript">Twitter visualization</a> tool (which feels a bit too much like a 2010 app). Since both CoffeeScript and Clojure are fun languages, and I wanted to see how ClojureScript would compare to CoffeeScript,  I took the challenge and crafted a simple game HTML5 physics based game on both languages, using <a href="http://code.google.com/p/box2dweb/">Box2dWeb</a>, a js port of Box2D (the physics engine, created by Erin Catto, that is behind <a href="http://www.geek.com/articles/mobile/box2d-creator-asks-rovio-for-angry-birds-credit-at-gdc-2011032/">Angry birds</a>).</p>
<p style="text-align:center;"><a href="http://danielribeiro.github.com/ClojureCoffeeScriptGame/" target="_blank"><img class="aligncenter size-medium wp-image-431" title="Game" src="http://metaphysicaldeveloper.files.wordpress.com/2011/08/game.png?w=300&#038;h=260" alt="" width="300" height="260" /></a></p>
<p>The <a href="http://danielribeiro.github.com/ClojureCoffeeScriptGame/">game</a> consists of clicking on the objects to destroy them, so that they don&#8217;t reach the top of the canvas (and, in another very Tetris like fashion, the elements pop out faster the more you play). It really sticks to the bare minimum of <a href="http://www.kocca.kr/knowledge/report/__icsFiles/afieldfile/2010/05/02/69912.pdf"><em>Terrano&#8217;s Hierarchy of Gamer Needs</em></a>. All the code is open source and can be fount on <a href="https://github.com/danielribeiro/ClojureCoffeeScriptGame">Github</a>. The <a href="https://github.com/danielribeiro/ClojureCoffeeScriptGame/blob/master/coffee/src/game.coffee">CoffeeScript</a>&#8216;s version source can be found here, and the <a href="https://github.com/danielribeiro/ClojureCoffeeScriptGame/blob/master/clojure/game.clj">ClojureScript</a>&#8216;s here.</p>
<h3>Lessons Learned</h3>
<p><em>Disclaimer</em><em>:</em> ClojureScript is pretty much in alpha status, so many things are likely to improve in the future.</p>
<p><strong>Compiling:</strong> The first thing that really pops up is how fast Coffeescript compiles down to JS. The watch behavior allows you to fire the compilation process and forget it. ClojureScript takes me about 5 seconds to compile a single file. Granted it gives warning about unused/undefined variables, but I&#8217;d really prefer it to compile instantly and let the browser tell me this on runtime.</p>
<p><strong>Namespaces:</strong> Clojure&#8217;s namespace are implemented as global variables, which are shadowed by local variables with the same name. For instance, if you are in a namespace called <em>game</em>, don&#8217;t use local variables and arguments named <em>game</em>. This is really important, as ClojureScript will use the global namespace for every single function defined in that namespace, so shadowing it is likely to give all sorts of errors.</p>
<p><strong>ClojureScript is not Clojure: </strong>Fogus wrote an interesting <a href="http://blog.fogus.me/2011/07/29/compiling-clojure-to-javascript-pt-2-why-no-eval/">piece</a> on the lack of eval on ClojureScript. Even though I find it might make sense for some web pages, when making WebGL games, or even Canvas 2d games, the assets size can easily overshadow then entire library&#8217;s size. Which is not a big deal if you use HTML5&#8242;s <a href="http://diveintohtml5.org/offline.html">Cache manifest</a>. In the end, it felt very much like the opposite of the Lisp spirit (epitomized by Paul Graham on his <span style="color:#000000;"><a href="http://news.ycombinator.com/item?id=2822177"><em>Five Questions about Language Design</em></a>: <em>&#8220;Give the Programmer as Much Control as Possible</em>&#8220;).</span></p>
<p>The documentation is <a href="https://github.com/clojure/clojurescript/wiki/Differences-from-Clojure">quite clear</a> that eval is not supported. What it is not clear, is that this argument against eval permeates many other functions: <a href="http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/resolve">resolve</a> is not implemented (neither ns-resolve, or the *ns* definition). Without both of them, there is no way to transform a string into a function. For people more used to OO languages, like Javascript, Ruby and Python, this essentially means that ClojureScript doesn&#8217;t have any reflection APIs. On the game:</p>
<p><pre class="brush: ruby; wrap-lines: false;">
createElement: -&gt;
  randomY = (0.2 + 0.4 * Math.random())*  H / @scale
  randomX = (Math.random() * (W - 50) + 25) / @scale
  type = @objectList[randomInt(@objectList.length)]
  @[&quot;create#{type}&quot;] randomX, randomY, Math.random() + 1
</pre></p>
<p>The last line of the Coffeescript version uses reflection to get the correct  method name (to decide to invoke createTriangle, createCircle or createSquare ). The ClojureScript version had to be translated into:</p>
<p><pre class="brush: ruby; wrap-lines: false;">
(defn- create-element [game]
  (let [randomY (/ (* H (+ 0.2 (* 0.4 (rand)))) scale)
        randomX (/ (+ 25 (* (rand) (- W 50))) scale)
        type (rand-nth [:circle :square :triangle])
        method (keyword (str &quot;create-&quot; (name type)))]
    ((@game method) game randomX randomY (inc (rand)))
    )
  )
</pre></p>
<p>Which is possible because the game has the respective functions as keyword attributes, which can be easily converted from string interpolation.</p>
<p><strong>User Macros are not supported</strong>: At the moment at least (support for it is likely to come on following updates). This makes the situation above much harder to take. But this is mostly due to ClojureScript&#8217;s alpha status. This does make the code a bit longer (the CoffeeScript version  has 236 lines, while the ClojureScript has 301 lines). In order to circumvent what I consider that  would be one of the ugliest bits caused by lack of macros (several <em>(set! (. obj attr) value)</em>  calls), I defined a js-set function:</p>
<p><pre class="brush: ruby; wrap-lines: false;">
(defn- js-set
  &quot;Sets an attribute name to a value on a javascript object
Returns the original object&quot;
  ([jsobject attr value]
    (do (native-set-wrapper jsobject attr value)
      jsobject))
  ([jsobject &amp; values]
    (do (doseq [[attr value] (apply hash-map values)]
          (native-set-wrapper jsobject attr value))
      jsobject)))
</pre></p>
<p>This is actually really against Clojure&#8217;s spirit, as Clojure really promotes immutable code. However Javascript libraries, in particular Box2dWeb, really expect mutable state. Therfore handling native js objects require such functions (note that converting them to clojure and keeping it on clojure land can be easily done with the nice undocumented function <em>js-&gt;clj</em> function, which is actually used on <a href="https://github.com/clojure/clojurescript/blob/master/samples/twitterbuzz/src/twitterbuzz/core.cljs">TwitterBuz</a>).</p>
<p>Therefore we can write functions this way</p>
<p><pre class="brush: ruby; wrap-lines: false;">
(defn- create-fixture
  ([shape] (js-set (b2FixtureDef.)
  :density 3
  :friction 0.3
  :restitution 0.9
  :shape shape
))
([] (create-fixture nil))
)

</pre></p>
<p>Instead of:</p>
<p><pre class="brush: ruby; wrap-lines: false;">
(defn- create-fixture
  ([shape] (let [f (b2FixtureDef.)]
  (set! (. f density) 3)
  (set! (. f friction) 0.3)
  (set! (. f restitution) 0.9)
  (set! (. f shape) shape)
))
([] (create-fixture nil)))
</pre></p>
<p>Which makes it look a lot like assoc function for creating maps with updated values. This version inspired me to refactor the Coffeescript version using a similar assoc function:</p>
<p><pre class="brush: ruby; wrap-lines: false;">
createFixture = (shape) -&gt;
f = new b2FixtureDef
f.density = 3.0
f.friction = .3
f.restitution = .9
f.shape = shape if shape?
return f
</pre></p>
<p>became:</p>
<p><pre class="brush: ruby; wrap-lines: false;">
assoc = (o, i) -&gt; o[k] = v for k, v of i; o

createFixture = (shape) -&gt;
assoc new b2FixtureDef,
density: 3
friction: .3
restitution: .9
shape: shape
</pre></p>
<p>Which is quite similar to ClojureScript&#8217;s version (the colons are on the right instead of the left, and it requires a comma). Which reduces the amount of <a href="http://blog.jayfields.com/2011/02/impact-of-accidental-complexity-on.html">accidental complexity</a> to a minimum.</p>
<p><em>Edit:</em> Thanks everybody for pointing out that you can use macros with Clojurescript. However, at the moment, the are clojure macros (so no js), and they require you hacking your clojurescript to add the macro files in the classpath. <a href="https://github.com/teropa/hiccups">Hiccups</a> and <a href="https://github.com/lynaghk/cljs-d3">cljs-3d</a> are two projects that do this, so you can see on their build files how they do this. Even then, you still need to use <a href="https://github.com/clojure/clojurescript/wiki/Differences-from-Clojure"><code>require-macros</code></a>. All of this makes macros less of a native feature on Clojurescript, and it makes a lot harder to share code seamlessly.</p>
<p><strong>IDE support:</strong> Clojure&#8217;s IDE support is really nice. Intellij&#8217;s <a href="http://plugins.intellij.net/plugin/?id=4050">La Clojure</a> (avaiable on its free Community Version) does a lot more than mere syntax highlight: minimal refactoring support, rainbow parenthesis, smart parenthesis, syntax highlighted repl, great autocomplete support, awesome code navigation, autocomplete for java classes and live templates. And it works pretty well for ClojureScript as well. Other <a href="http://dev.clojure.org/display/doc/Getting+Started">IDEs are also great</a>, even though Emacs support can be a bit more intense on its setup (which is not something emacs users are unfamiliar with).</p>
<p>Even though I am really happy with Github&#8217;s founder Chris Wanstrath work on the <a href="https://github.com/defunkt/coffee-mode">Emacs mode for Coffeescript</a>, it doesn&#8217;t have the same support that Clojure does. It is getting more and <a href="https://github.com/jashkenas/coffee-script/wiki/Text-editor-plugins">more support</a>, but nowadays Clojure has the upper hand.</p>
<p><strong>Debugging support:</strong> Browser support for debugging languages that compile down to javascript is <a href="http://www.infoq.com/news/2011/08/debug-languages-on-javascript-vm">coming</a>, but at the moment Cofffeescript compiles down to such a readable JS that it not a big problem. This is a <a href="https://groups.google.com/forum/#!topic/clojure/USoSFlNrMwM">known</a> issue with ClojureScript at the moment. Even on pretty print compile mode.</p>
<h3>Conclusions</h3>
<p>Since Javascript on the web has a much more simple <a href="http://ejohn.org/blog/how-javascript-timers-work/">execution model</a> than Java, Clojure&#8217;s amazing concurrency control mechanisms are not as shining. Nevertheless ClojureScript is a delight to work with. As it moves out of its Alpha status, many of the issues are likely to be gone. I also expect it to support the full Clojure language (including things like resolve, letfn, macros and eval), as writing web apps in a single language on client and server is a really nice feature. This would also make ClojureScript even more interesting, as it would allow developers do leverage all the power of existing Clojure libraries into their Javascript work (and possibly use it on a more polyglot environment).</p>
<p>Coffeescript is more suitable for production apps right now, but it  is nice to see all these developer efforts to allow people to be more productive and happy with their work on Javascript platforms (this way we don&#8217;t have to wait for Google&#8217;s <a href="http://chrome.blogspot.com/2011/08/building-better-web-apps-with-new.html">NaCl</a> and <a href="http://nativeclient.googlecode.com/svn/data/site/pnacl.pdf">PNaCL</a>, which promise to bring even more languages to the environment).</p>
<br /> Tagged: <a href='http://metaphysicaldeveloper.wordpress.com/tag/clojure/'>clojure</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/coffeescript/'>coffeescript</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/html5/'>html5</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/420/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/420/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/metaphysicaldeveloper.wordpress.com/420/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/metaphysicaldeveloper.wordpress.com/420/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/metaphysicaldeveloper.wordpress.com/420/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/metaphysicaldeveloper.wordpress.com/420/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/metaphysicaldeveloper.wordpress.com/420/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/metaphysicaldeveloper.wordpress.com/420/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/metaphysicaldeveloper.wordpress.com/420/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/metaphysicaldeveloper.wordpress.com/420/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/metaphysicaldeveloper.wordpress.com/420/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/metaphysicaldeveloper.wordpress.com/420/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/metaphysicaldeveloper.wordpress.com/420/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/metaphysicaldeveloper.wordpress.com/420/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=420&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2011/08/28/clojurescript-vs-coffeescript/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/08/rome.png" medium="image">
			<media:title type="html">Rome project</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/08/game.png?w=300" medium="image">
			<media:title type="html">Game</media:title>
		</media:content>
	</item>
		<item>
		<title>Hacking a Gnuplot into Minecraft</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2011/07/31/hacking-a-gnuplot-into-minecraft/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2011/07/31/hacking-a-gnuplot-into-minecraft/#comments</comments>
		<pubDate>Mon, 01 Aug 2011 02:58:44 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[hacking]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=386</guid>
		<description><![CDATA[For those who don&#8217;t know, Minecraft is an inspiring indie game that places the gamer into a sandbox 3d world, where everything is made of blocks. Blocks can also be crafted into other blocks through recipes. Besides having over 10 million users and being feature on Techcrunch, what makes it quite unique is what the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=386&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>For those who don&#8217;t know, <a href="http://www.minecraft.net/">Minecraft</a> is an inspiring indie game that places the gamer into a sandbox 3d world, where everything is made of blocks. Blocks can also be crafted into other blocks through recipes. Besides having over <a href="http://notch.tumblr.com/post/7128013309/10m">10 million</a> users and being feature on <a href="http://techcrunch.com/2011/01/15/a-brief-explanation-of-why-minecraft-matters/">Techcrunch</a>, what makes it quite unique is what the users have created with it: from a 3d block replica of <a href="http://www.youtube.com/watch?v=kn2-d5a3r94">the enterprise</a>, to <a href="http://www.youtube.com/watch?v=yKEbBX21igc">giant spaceships</a> and entire <a href="http://www.youtube.com/watch?v=yxAmphwLPDY">8 bit CPUs</a>. Users even created a real time <a href="http://www.youtube.com/watch?v=x2mCDkqXki0">kinetic world</a> terraformer, a tool that lets you use a <a href="http://minecraftprint.com/">3d printer</a> to bring to physical world creations from minecraft, and tools to import good old fashioned <a href="//www.patrickmin.com/minecraft/">3d models</a> into minecraft.</p>
<p>As expected, Minecraft has its <a href="http://www.minecraftwiki.net/wiki/Programs_and_editors">tools</a> and <a href="http://www.minecraftwiki.net/wiki/Mods">mods</a>. And even though there are several libs for view the world of a save file, I found that, in spite of its vibrant community, there were no libs for editing the world. Note that <a href="http://davidvierra.com/mcedit.html">MCEdit</a> allows some  hacking, but it is mostly a GUI editor (and a very good one in my opinion).</p>
<p>So I hacked together a simple library for manipulating the world files called <a href="https://github.com/danielribeiro/RubyCraft">RubyCraft</a>. To illustrate the simplicity it enables, turning the first chunk completely into gold is a simple one line:</p>
<p><pre class="brush: ruby; wrap-lines: false;">
Region.fromFile(filename).chunk(0, 0).block_map { :gold }
</pre></p>
<p>And making all blocks into orange wool is as simple as</p>
<p><pre class="brush: ruby; wrap-lines: false;">
Region.fromFile(filename).chunk(0, 0).each do |b|
  b.name = :wool
  b.color = :orange
end
</pre></p>
<p>The result:</p>
<p style="text-align:center;"><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/orangeTower.png"><img class="aligncenter" title="orange tower" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/orangeTower.png" alt="" width="426" height="324" /></a></p>
<p>The issue with this Api is that it leaks a bit the Minecraft abstraction of how the world is divided. In a nutshell, the world is divided into <em>region</em> files, each one is divided into a 32 x 32 matrix of <em>chunks</em>, which is nothing more than a 16x16x128 cube of blocks. To manipulate the chunks inside a region file, you can request a <a href="https://github.com/danielribeiro/RubyCraft/blob/master/lib/rubycraft/region.rb#L112">cube</a>, giving its initial point, width, length and height. The same code above could be written ignoring the chunk abstraction like this:</p>
<p><pre class="brush: ruby; wrap-lines: false;">
r = Region.fromFile(filename)
c = r.cube(0, 0, 0, :width =&gt; 16, :length =&gt; 16, :height =&gt; 128)
c.each do |block, z, x, y|
  block.name = :wool
  block.color = :orange
end
</pre></p>
<p>A cube can span several chunks, but at the moment it can&#8217;t span several regions. It might not be a big issue, as a Region is a pretty large area (it contains <em>over</em> 33 million blocks), and it can take a while to save an entire region (the time it takes to save a Region is proportional to the changed chunks), even in <a href="http://www.jruby.org/">JRuby</a> (which I found to be 3 times as fast than MRI for this particular task).</p>
<h3><span style="text-decoration:underline;">A Gnuplot in my Minecraft</span></h3>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/plottingOverview.png"><img class="aligncenter" title="overview" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/plottingOverview.png" alt="" width="426" height="324" /></a></p>
<p><em>Edit</em>: The save file for the resulting world can be found <a href="http://dl.dropbox.com/u/37205964/PlottedLowDirt.zip">here</a>.</p>
<p>After turning Minecraft world file into a 3d matrix, making a two real function plotter quite simple. The <a href="https://github.com/danielribeiro/RubyCraft/blob/master/examples/plotting_example.rb#L73">plotting_example.rb</a> mostly contains code that decide the area where the graph will be plotted, centering the function on the xz axis, and more importantly, it plots f(x, y) for a given f:</p>
<p><pre class="brush: ruby; wrap-lines: false;">
def plot(function, fillFunction)
cube = getCube
middlePointX = length / 2
middlePointZ = width / 2
centeredF = proc do |x, z|
function.call(x - middlePointX, z - middlePointZ).ceil
end
points = Set.new
yzraster(centeredF, points)
yxraster(centeredF, points)
modifyBlocks(cube, centeredF, fillFunction, points)
end
</pre></p>
<p>Quite straightforward. The functions yxraster and yzraster have a mild subtlety: just plotting the points of f(x, y) can prevent a look from looking continuous. In general plotting algorithms you have to find a plane or another elementary surface to approximate a small region. As minecraft only contains blocks, I&#8217;ve joined all points by discrete line segments, using <a href="http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm">Bresenham&#8217;s line algorithm</a> (source <a href="https://github.com/danielribeiro/RubyCraft/blob/master/examples/example_helpers.rb#L22">here</a>). This is done by transversing the plotting cube with xy planes, and then with zy planes (therefore only the 2d version of Bresenham algorithm is needed).</p>
<p>Also note that f(x, y) is coerced into integer values by taking the ceil. This is because Bresenham&#8217;s algorithm expects points defined on Z x Z, but is expected, as the resulting points would have to be coerced into a integer y coordinate anyway because of the Minecraft world definition.</p>
<p>With all of  this, the following <a href="https://github.com/danielribeiro/RubyCraft/blob/master/examples/plotting_example.rb#L6">examples</a> are easy to create:</p>
<p>Diamond Cone:</p>
<p><pre class="brush: ruby; wrap-lines: false;">
plotWith :diamond_block do |x, z|
   sqrt((x** 2 + z ** 2) / 3) * 5 + 20
end
</pre></p>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/cone.png"><img class="aligncenter" title="cone" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/cone.png" alt="" width="426" height="324" /></a></p>
<p>Water Hyperbolic Paraboloid</p>
<p><pre class="brush: ruby; wrap-lines: false;">
    plotWith :water do |x, z|
      (x** 2 - z ** 2) / 3 + 50
    end
</pre></p>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/hyperbolicParaboloid.png"><img class="aligncenter" title="hyperbolicParaboloid" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/hyperbolicParaboloid.png" alt="" width="426" height="324" /></a></p>
<p>Lava <a href="http://gnuplot.sourceforge.net/demo_4.4/surface1.10.png">Surface 10 of Gnuplot examples</a></p>
<p><pre class="brush: ruby; wrap-lines: false;">
    plotWith :lava do |x, z|
      log(x ** 4 * z ** 2 + 2) + 20
    end
</pre></p>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/gnuplotSurface10.png"><img class="aligncenter" title="gnuplotSurface10" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/gnuplotSurface10.png" alt="" width="426" height="324" /></a></p>
<p>Netherrack <a href="http://gnuplot.sourceforge.net/demo_4.4/surface1.15.png">Surface15 of Gnuplot examples</a></p>
<p><pre class="brush: ruby; wrap-lines: false;">
    plotWith :netherrack do |x, z|
      (sin(sqrt(z ** 2 + z ** 2)) / sqrt(x ** 2 + z ** 2)) * 30 + 30
    end
</pre></p>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/gnuplotSurface15.png"><img class="aligncenter" title="gnuplotSurface15" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/gnuplotSurface15.png" alt="" width="426" height="324" /></a></p>
<p>Golden rotated Sine</p>
<p><pre class="brush: ruby; wrap-lines: false;">
    plotWith :gold do |x, z|
      sin(sqrt((x** 2 + z ** 2)) / 2) * 10 + 30
    end
</pre></p>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/rotatedSine.png"><img class="aligncenter" title="rotatedSine" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/rotatedSine.png" alt="" width="426" height="324" /></a></p>
<p>Ice Sphere (half sphere actually)</p>
<p><pre class="brush: ruby; wrap-lines: false;">
    plotWith :ice do |x, z|
      sqrt(18**2 - x**2 - z **2) + 30
    end
</pre></p>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/halfSphere.png"><img class="aligncenter" title="halfSphere" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/halfSphere.png" alt="" width="426" height="324" /></a></p>
<p>Wooden Polynomial</p>
<p><pre class="brush: ruby; wrap-lines: false;">
    plotWith :log do |x, z|
      x /= 5
      z /= 5
      (x + z) ** 5 + x**3 + z**2 + 30
    end
</pre></p>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/polynomial.png"><img class="aligncenter" title="polynomial" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/polynomial.png" alt="" width="426" height="324" /></a></p>
<p>Obysidan Polynomial Quotient</p>
<p><pre class="brush: ruby; wrap-lines: false;">
    plotWith :obsidian do |x, z|
      p1 = (x + z) ** 6 - x ** 3 + z **2 + 50
      p2 = x ** 7 + 6* z ** 6 - x **4 - z**2 + 30
      p1 / p2 + 10
    end
</pre></p>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/polynomialQuotient.png"><img class="aligncenter" title="polynomialQuotient" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/polynomialQuotient.png" alt="" width="426" height="324" /></a></p>
<p>Colorful Paraboloid</p>
<p><pre class="brush: ruby; wrap-lines: false;">
    plot(proc {|x, z| (x** 2 + z ** 2) / 3}, proc do |b, z, x, y|
        b.name = :wool; b.data = OrderedColors[y * 16 / 128].data
      end)
</pre></p>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/paraboloid.png"><img class="aligncenter" title="paraboloid" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/paraboloid.png" alt="" width="426" height="324" /></a></p>
<p>The Ordered Colors of the Colorful Paraboloid are the <a href="http://www.minecraftwiki.net/wiki/Data_values#Wool">Wool Colors</a> of minecraft sorted by distance to the black color. The distance <a href="http://www.orderofevents.com/MineCraft/Phase3/processImages.py">definition</a> is the same as the one from the <a href="http://www.orderofevents.com/MineCraft/KinectInfo.htm">kinetic experiment</a>.</p>
<p>The <a href="https://github.com/danielribeiro/RubyCraft/blob/master/examples/plotting_example.rb#L73">plotting class</a> cannot plot parametric surfaces at the moment. However, since the graphs are real minecraft objects, they can be manipulated as any other minecraf object. For instance, it is possible to turn the golden rotated sine into a roller coaster (<a href="https://github.com/danielribeiro/RubyCraft/blob/master/examples/roller_coaster.rb">source here</a>):<br />
<a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/goldSineRollerCoaster.png"><img class="aligncenter" title="goldSineRollerCoaster" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/goldSineRollerCoaster.png" alt="" width="426" height="324" /></a></p>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/onthesineRollerCoaster.png"><img class="aligncenter" title="onthesineRollerCoaster" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/onthesineRollerCoaster.png" alt="" width="426" height="324" /></a></p>
<p>All the code is open source and can be fount on <a href="https://github.com/danielribeiro/RubyCraft">Github</a>.</p>
<h3>Acknowledgements</h3>
<p>The examples use an edited version of the <a href="http://www.minecraftforum.net/topic/121011-creation-tykens-test-world-v181-15-updates/">Low Dirt Tyken</a>&#8216;s test world. The screenshots were take while flying using <a href="http://www.minecraftforum.net/topic/94310-173-single-player-commands-v210-2">Single Player Commands mod</a>. The algorithm for parsing the region file was based on <a href="http://clockworkcodex.blogspot.com/2011/06/minecraft-mapping-reading-minecraft.html">Weeble&#8217;s work</a>. Parsing the nbt binary is done through <a href="https://github.com/mental/nbtfile">NbtFile</a> gem.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/386/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/386/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/metaphysicaldeveloper.wordpress.com/386/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/metaphysicaldeveloper.wordpress.com/386/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/metaphysicaldeveloper.wordpress.com/386/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/metaphysicaldeveloper.wordpress.com/386/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/metaphysicaldeveloper.wordpress.com/386/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/metaphysicaldeveloper.wordpress.com/386/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/metaphysicaldeveloper.wordpress.com/386/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/metaphysicaldeveloper.wordpress.com/386/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/metaphysicaldeveloper.wordpress.com/386/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/metaphysicaldeveloper.wordpress.com/386/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/metaphysicaldeveloper.wordpress.com/386/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/metaphysicaldeveloper.wordpress.com/386/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=386&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2011/07/31/hacking-a-gnuplot-into-minecraft/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/orangeTower.png" medium="image">
			<media:title type="html">orange tower</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/plottingOverview.png" medium="image">
			<media:title type="html">overview</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/cone.png" medium="image">
			<media:title type="html">cone</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/hyperbolicParaboloid.png" medium="image">
			<media:title type="html">hyperbolicParaboloid</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/gnuplotSurface10.png" medium="image">
			<media:title type="html">gnuplotSurface10</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/gnuplotSurface15.png" medium="image">
			<media:title type="html">gnuplotSurface15</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/rotatedSine.png" medium="image">
			<media:title type="html">rotatedSine</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/halfSphere.png" medium="image">
			<media:title type="html">halfSphere</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/polynomial.png" medium="image">
			<media:title type="html">polynomial</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/polynomialQuotient.png" medium="image">
			<media:title type="html">polynomialQuotient</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/paraboloid.png" medium="image">
			<media:title type="html">paraboloid</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/goldSineRollerCoaster.png" medium="image">
			<media:title type="html">goldSineRollerCoaster</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/onthesineRollerCoaster.png" medium="image">
			<media:title type="html">onthesineRollerCoaster</media:title>
		</media:content>
	</item>
		<item>
		<title>Peter Norvig&#8217;s Spelling Corrector in 21 Lines of Coffeescript</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2011/03/31/354/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2011/03/31/354/#comments</comments>
		<pubDate>Thu, 31 Mar 2011 04:14:03 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[Languages]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=354</guid>
		<description><![CDATA[Coffeescript is a very nice (and relatively new) language that compiles down to javascript, making web programming (and making firefox plugins, nodejs apps, and so forth) much more joyful. Its object model is the same as javascript (one of coffeescript&#8217;s motto is Unfancy JavaScript), and its compiled js form is quite easy to read and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=354&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://jashkenas.github.com/coffee-script/">Coffeescript</a> is a very nice (and relatively new) language that compiles down to javascript, making web programming (and making firefox plugins, nodejs apps, and so forth) much <a href="http://amix.dk/blog/post/19612">more joyful</a>. Its object model is the same as javascript (one of coffeescript&#8217;s <a href="https://github.com/jashkenas/coffee-script">motto</a> is <em>Unfancy JavaScript</em>), and its compiled js form is quite easy to read and debug. It has many <a href="http://jashkenas.github.com/coffee-script/#overview">niceties</a>, including <a href="http://jashkenas.github.com/coffee-script/#classes">classes</a> (effectively making the <a href="http://mckoss.com/jscript/object.htm">prototype chain</a> a first class citizen of the language) and <a href="http://jashkenas.github.com/coffee-script/#loops">array/object comprehensions</a> (heavily influenced by python&#8217;s <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">list comprehensions</a>).</p>
<p>Ruby also has a influence on the language, such as <a href="http://jashkenas.github.com/coffee-script/#language">optional parenthesis</a> on method/function invocation. In fact, the original version of Coffeescript compiler was <a href="http://www.rubyinside.com/coffeescript-a-new-language-with-a-pure-ruby-compiler-2921.html">written in Ruby</a> (but nowadays coffeescript is a <a href="http://en.wikipedia.org/wiki/Bootstrapping_(compilers)">self-hosting</a> language).</p>
<p>Coffeescript has been used by several <a href="http://jashkenas.github.com/coffee-script/#resources">projects</a>, including a <a href="http://thinkvitamin.com/mobile/new-rails-like-framework-from-37signals-for-html5-mobile-apps/">mobile framework</a> written by Rail&#8217;s creator <a href="http://37signals.com/">37 signals</a>. I&#8217;ve been using for about one year (including some open source <a href="https://github.com/danielribeiro/EaselBugTracker/blob/master/lib/easelbugtracker.coffee">work</a> using a HTML 5 Canvas framework called <a href="http://easeljs.com/">EaselJs</a>, a port of <a href="https://github.com/danielribeiro/rbcoffee/blob/master/rbcoffee.coffee">ruby functionalities</a> and even a <a href="https://github.com/danielribeiro/powerhistory">Firefox plugin</a>).</p>
<p>Because of all the Ruby and Python influence on the language, and the fact that Coffeescript can convey beautiful and concise code, I had a hunch that it could get a really good position on <a href="http://norvig.com/spell-correct.html">Peter Norvig&#8217;s Spelling Corrector</a> implementation collection (Javascript&#8217;s <a href="http://astithas.blogspot.com/2009/08/spell-checking-in-javascript.html">version</a> currently has 53 lines, which is a lot more than <a href="http://norvig.com/spell.py">python</a>&#8216;s 21). With some work, I managed to implement it in 21 lines as well:</p>
<p><pre class="brush: ruby; wrap-lines: false;">
words = (text) -&gt; (t for t in text.toLowerCase().split(/[^a-z]+/) when t.length &gt; 0)
Array::or = (arrayFunc) -&gt; if @length &gt; 0 then @ else arrayFunc()
Array::flat = -&gt; if @length == 0 then @ else @[0].concat(@[1..].flat())
train = (features) -&gt;
 model = {}
 (model[f] = if model[f] then model[f] +1 else 2) for f in features
 return model
NWORDS = train(words(require('fs').readFileSync('./lib/big.txt', 'utf8')))
alphabet = 'abcdefghijklmnopqrstuvwxyz'.split &quot;&quot;
edits1 = (word) -&gt;
 s = ([word.substring(0, i), word.substring(i)] for i in [0..word.length])
 deletes = (a.concat b[1..] for [a, b] in s when b.length &gt; 0)
 transposes = (a + b[1] + b[0] + b.substring(2) for [a, b] in s when b.length &gt; 1)
 replaces = (a + c + b.substring(1) for c in alphabet for [a, b] in s when b.length &gt; 0)
 inserts = (a + c + b for c in alphabet for [a, b] in s)
 return deletes.concat transposes.concat replaces.flat().concat inserts.flat()
known_edits2 = (word) -&gt; ((e2 for e2 in edits1(e1) when NWORDS[e2]? for e1 in edits1(word)).flat())
known = (words) -&gt; (w for w in words when NWORDS[w])
correct = (word) -&gt;
 candidates = known([word]).or -&gt; known(edits1(word)).or -&gt; known_edits2(word).or -&gt; [word]
 ({k: w, v: NWORDS[w] or 1} for w in candidates).sort((a, b)-&gt; b.v  - a.v)[0].k
</pre></p>
<p>All the code is hosted on <a href="https://github.com/danielribeiro/Coffeescript-Spelling-Corrector">github</a>. The code above can be seen in a more readable version <a href="https://github.com/danielribeiro/Coffeescript-Spelling-Corrector/blob/master/lib/spellCheck.coffee">here</a> (after line 21 it also contains a full test, using a fixture generated by a <a href="https://github.com/danielribeiro/Coffeescript-Spelling-Corrector/blob/master/python/spell.py">slightly modified version</a> of Peter Norvig&#8217;s original implementation). There is a more <a href="https://github.com/danielribeiro/Coffeescript-Spelling-Corrector/blob/master/lib/testableSpellCheck.coffee">testable</a> version, along with <a href="http://pivotal.github.com/jasmine/">Jasmine</a> BDD <a href="https://github.com/danielribeiro/Coffeescript-Spelling-Corrector/blob/master/spec/coffee/spellCheckSpec.coffee">tests</a> (which look a lot like Rspec&#8217;s in Coffeescript), which run headless on NodeJs, but work just fine in the browsers.</p>
<h3>Considerations</h3>
<p>Findall regex doesn&#8217;t exists natively in Javascript, however it is equivalent to spiting by the complementary regex (line 1)</p>
<p>Array::or (line 2) was needed to be implemented, because Python&#8217;s truthfulness allows a collection to be true (actually, any iterable) as long as it is not empty. Array::flat (line 3) has to be implemented because Coffeescript&#8217;s loop comprehension is a bit different from python&#8217;s: double loops (example: <em>x + y for y in col1 for z in col2</em>) return array of arrays instead of a single array.</p>
<p>Also note that loop comprehension&#8217;s order is inverted (<em>x + y for x for y</em> in python is translated as <em>x + y for y for x</em>).</p>
<p>Granted, this version runs really fast on NodeJs 0.4.1, and I was quite happy with how the resulting code looked. I was even happier that I did not have to write the compiled <a href="https://github.com/danielribeiro/Coffeescript-Spelling-Corrector/blob/master/libjs/spellCheck.js">Javascript</a> file and its whooping 147 lines of Spelling Corrector.</p>
<p>To see the reason why this work, check out Peter Norvig&#8217;s<a href="http://norvig.com/spell-correct.html"> original post</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/354/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/354/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/metaphysicaldeveloper.wordpress.com/354/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/metaphysicaldeveloper.wordpress.com/354/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/metaphysicaldeveloper.wordpress.com/354/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/metaphysicaldeveloper.wordpress.com/354/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/metaphysicaldeveloper.wordpress.com/354/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/metaphysicaldeveloper.wordpress.com/354/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/metaphysicaldeveloper.wordpress.com/354/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/metaphysicaldeveloper.wordpress.com/354/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/metaphysicaldeveloper.wordpress.com/354/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/metaphysicaldeveloper.wordpress.com/354/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/metaphysicaldeveloper.wordpress.com/354/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/metaphysicaldeveloper.wordpress.com/354/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=354&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2011/03/31/354/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>
	</item>
		<item>
		<title>High Level Concurrency with JRuby and Akka Actors</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2010/12/16/high-level-concurrency-with-jruby-and-akka-actors/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2010/12/16/high-level-concurrency-with-jruby-and-akka-actors/#comments</comments>
		<pubDate>Fri, 17 Dec 2010 01:46:21 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[Systems]]></category>
		<category><![CDATA[actors]]></category>
		<category><![CDATA[akka]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=300</guid>
		<description><![CDATA[Many developers are used to low-level concurrency primitives, such as locks, monitors and semaphores. Java also has higher level concurrency utilities such as Atomic Objects and Fork/Join framework. Such primitives still require a lot of attention to shared variables, and are very easy to get wrong. Ilya Grigorik recently discussed other models of concurrency on [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=300&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Many developers are  used to low-level <a href="http://en.wikipedia.org/wiki/Concurrency_%28computer_science%29">concurrency</a> primitives, such as <a href="http://en.wikipedia.org/wiki/Mutual_exclusion">locks</a>, <a href="http://en.wikipedia.org/wiki/Monitor_%28synchronization%29">monitors</a> and <a href="http://en.wikipedia.org/wiki/Semaphore_%28programming%29">semaphores</a>. Java also has higher level concurrency utilities such as <a href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/package-summary.html">Atomic Objects</a> and <a href="http://gee.cs.oswego.edu/dl/papers/fj.pdf">Fork/Join</a> framework. Such primitives still require a lot of attention to shared variables, and are very easy to get wrong.  Ilya Grigorik recently discussed other models of concurrency on his recent post <em><a href="http://www.igvita.com/2010/12/02/concurrency-with-actors-goroutines-ruby/?utm_source=feedburner&amp;utm_campaign=Feed%3A+igvita+%28igvita.com%29&amp;utm_content=feed">Concurrency with Actors, Goroutines &amp; Ruby</a></em>, where he even introduced a ruby port of <a href="http://golang.org/">Go</a>&#8216;s concurrency mechanism. These models attempt to make concurrent programming easier.</p>
<p>The <a href="http://en.wikipedia.org/wiki/Actor_model">actor model</a> is another very simple high level concurrency model: actors can&#8217;t respond to more than one message at a time (messages are queued into mailboxes) and can only communicate by sending messages, not sharing variables. As long as the messages are <a href="http://doc.akkasource.org/untyped-actors-java#Actors%20%28Java%29-Messages%20and%20immutability">immutable</a> data structures (which is always true in Erlang, but has to be a convention in languages without means of ensuring this property), everything is thread-safe, without need for any other mechanism. This is very similar to request cycle found in web development MVC frameworks.</p>
<p><a title="Scala: The Successor to the Throne" href="http://metaphysicaldeveloper.wordpress.com/2009/07/29/scala-the-successor-to-the-throne/">Scala</a> is famous for coming with an Actor library built-in. However, using Scala libraries in Ruby is not easy[1]. <a href="http://akkasource.org/">Akka</a> is another great project that implements Actors, however it has a <a href="http://doc.akkasource.org/untyped-actors-java">java Api</a>, which makes the JRuby integration easier. Why JRuby? Not only to access Akka&#8217;s actor library, but also because JRuby is one of the few ruby implementations that doesn&#8217;t have the <a href="http://www.igvita.com/2008/11/13/concurrency-is-a-myth-in-ruby/">GIL</a>, therefore it allows true concurrency for all types of applications (IO bounded or not).</p>
<h4><span style="text-decoration:underline;"><strong>Integrating Akka with JRuby</strong></span></h4>
<p>For starters, let&#8217;s first create a simple actor in Java:</p>
<p><pre class="brush: java;">
public class PingActor extends UntypedActor {
	public void onReceive(Object message) throws Exception {
	    if (message instanceof String) {
	    	System.out.println(&quot;!!! Acted on: &quot; + message);
	    }
	    else throw new IllegalArgumentException(&quot;Unknown message:&quot; + message);
	}
}
</pre></p>
<p>This simple actor will just output any message it receives prefixed with &#8220;!!! Acted on: &#8220;, and will throw exception on any message that is not a string. This example show how simple it is to define an actor: just define a onReceive method that is called whenever a message is sent.</p>
<p>To see this actor working, we need four lines:</p>
<p><pre class="brush: java;">
		ActorRef actor = actorOf(PingActor.class).start();
		actor.sendOneWay(&quot;hello actor world&quot;);
		TimeUnit.SECONDS.sleep(1);
		ActorRegistry.shutdownAll();
</pre></p>
<p>The first gets an actor reference and starts it. It is important to note that you cannot create an actor just by invoking new. Not in java or scala (we can solve this in Ruby). This is because there is a lot of AOP going on the background[2]. The second line just sends the message to the actor asynchronously. There two other ways of sending messages, which I&#8217;ll not cover, but you can <a href="http://doc.akkasource.org/untyped-actors-java#Actors%20%28Java%29-Send%20messages">read more</a> in Akka&#8217;s documentation.</p>
<p>The last two lines just give time to the message reach the actor (remember, the sendOneWay method is non-blocking), and stops all actors on the system. Pretty simple right? Let&#8217;s see how we can do the same in JRuby. Setting up the stage:</p>
<p><pre class="brush: ruby;">
require 'java'
module Akka
  include_package 'se.scalablesolutions.akka.actor'
end
</pre></p>
<p>These lines enable java and make a ruby module with all the classes of se.scalablesolutions.akka.actor package. Basic JRuby setup. Now on to defining the actor:</p>
<p><pre class="brush: ruby;">class PingActor &lt; Akka::UntypedActor
  def self.create(*args)
    self.new(*args)
  end

  def onReceive(message)
    puts &quot;!!! Acted on: #{message}&quot;
  end
end
</pre></p>
<p>Here we have our first differences. The onReceive is just a cleaner version of the Java one. No type annotations, no type checking and a simpler string output. However, we have to define a <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/wont_work_without_create.rb">classmethod called create</a>, which just invokes new. This method seems to be created by the AOP part of Akka, which doesn&#8217;t seem to work on Ruby subclasses of UntypedActor. However, we can defined it ourselves. Now to actually using the actor:</p>
<p><pre class="brush: ruby;">
actor = Akka::UntypedActor.actorOf(PingActor).start
actor.sendOneWay &quot;hello actor world&quot;
sleep 1
Akka::ActorRegistry.shutdownAll
</pre></p>
<p>Pretty much the same four lines as on the Java version, with a little less parenthesis, and a terser sleep method. The ruby code can be found on <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/basic_example.rb">this page</a>, and Java code <a href="https://github.com/danielribeiro/RubyOnAkka/tree/master/java/helloakka">here</a>.</p>
<h4><span style="text-decoration:underline;"><strong><strong>Fixing the Ruby Interface</strong></strong></span></h4>
<p>Much of the code in the former example is infrastructure, but we can work around the static nature of Java classes in ruby. As factored out in <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/akka.rb">akka.rb</a>,  we can gather this functionalities into a base class, and rewrite the first example in <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/fixxed_basic_example.rb">8 lines</a>:</p>
<p><pre class="brush: ruby;">require 'akka'
class PingActor &lt; Actors::Base
  def onReceive(message)
    puts &quot;!!! Acted on: #{message}&quot;
  end
end
PingActor.spawn.sendOneWay &quot;hello actor world&quot;
Actors.delayedShutdown 1
</pre></p>
<p>Using closures we can even enhance our JRuby api with some ideas from the Scala api, making it <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/proc_basic_example.rb">down to 3 lines</a>:</p>
<p><pre class="brush: ruby;">require 'akka'
Actors.spawn { |m| puts &quot;!!! Acted on: #{m}&quot; }.sendOneWay &quot;hello actor world&quot;
Actors.delayedShutdown 1
</pre></p>
<p>In this example spawn takes a block, and creates an actor that executes it every time it receives a message. As in the Scala API, spawn starts the actor as well as creating it.</p>
<h4><span style="text-decoration:underline;"><strong><strong>But every Object is an Actor!</strong></strong></span></h4>
<p>Alan Kay, the inventor of Smalltak and of the <a href="http://c2.com/cgi/wiki?AlanKayOnObjects">term OO</a>, once <a href="http://c2.com/cgi/wiki?AlanKayOnMessaging">said</a>:</p>
<p style="padding-left:30px;"><em>I&#8217;m sorry that I long ago coined the term &#8220;objects&#8221; for this topic because it gets many people to focus on the lesser idea. The big idea is &#8220;messaging&#8221;.</em></p>
<p>This is one of the reasons that Erlang with its actors form an object oriented language[3]</p>
<p>If we look into the resemblance of sendOneWay and the reflective method invocation, which in Ruby is made through <a href="http://ruby-doc.org/core-1.8.7/classes/Object.html#M000606">send</a> or __send__, it is quite easy to adapt the ruby method invocation to Actor message sending. We start with a simple <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/akka.rb#L35">delegator</a>:</p>
<p><pre class="brush: ruby;">MethodParameters = Struct.new :name, :args, :block

class DelegatorActor &lt; Base
    def self.new(target)
      ret = super()
      ret.instance_variable_set(:@target, target)
      return ret
    end

    def onReceive(message)
      param = message
      @target.__send__ param.name, *param.args, &amp;param.block
    end
  end
</pre></p>
<p>The important part is the onRecieve message, which takes a MethodParameters object and invoke on the target. The caveat here is that we need to override the new method, because, for some reason, ruby subclasses of Akka UntypedActors will not invoke the initialize method with the arguments passed[4]. However, by turning any object into an actor, this can be the only place such hack is needed.</p>
<p>Now, the next step: <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/akka.rb#L52">adapting the actorRefs</a> to make the ruby method invocation a actor sendOneWay:</p>
<p><pre class="brush: ruby;">class ActorRefHandler
    public_instance_methods.each do |m|
      undef_method m unless m =~ /^__/ or m == 'to_s'
    end

    def initialize(actorRef)
      @actorRef = actorRef
    end

    def method_missing(name, *args, &amp;block)
      @actorRef.sendOneWay MethodParameters.new name, args, block
    end
  end
</pre></p>
<p>Which is a pretty standard implementation of message forwarding in ruby: remove all instance methods (except the really private ones, such as __send__), making sure all method calls are forwarded to method_missing.</p>
<p>With all of this we can write a simple example of <a href="//github.com/danielribeiro/RubyOnAkka/blob/master/lib/everything_is_an_actor.rb">making any object an actor</a>:</p>
<p><pre class="brush: ruby;">require 'akka'
class HelloWord
  def hi
    puts &quot;hello actor world&quot;
  end
end
Actors.actorOf(HelloWord.new).hi
Actors.delayedShutdown 1
</pre></p>
<h4><span style="text-decoration:underline;"><strong><strong><strong><strong>Making it faster</strong></strong></strong></strong></span></h4>
<p>In the heart of all of this lies the problem: making code runs faster by using the machine&#8217;s cores more effectively. Here we build the good old canonical <a href="http://hadoop.apache.org/common/docs/r0.20.2/mapred_tutorial.html#Example%3A+WordCount+v1.0">map-reduce example: word count</a>. We will count 5.4 MB of <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/shakespeare.txt">Shakespeare</a>&#8216;s texts. The example consists of 3 types of actors: a producer, mappers, and one reducer. The producer generates the chunks of lines to the mappers, which count the words on each chunk and generate a hash of word:count pairs, which the reducer aggregates into a hash of its own.</p>
<p><pre class="brush: ruby;">require 'akka'
require 'regular_word_count'
include Actors
module AkkaDispatcher
  include_package 'se.scalablesolutions.akka.dispatch'
  def self.workStealer(name)
    Dispatchers.newExecutorBasedEventDrivenWorkStealingDispatcher 'mappers'
  end
end

file = File.join(File.dirname(__FILE__), 'shakespeare.txt')
input = IO.readlines(file).each_slice(500).map &amp;:join
</pre></p>
<p>This code setups up the code to later define WorkStealer, so that our map actors can share the same message queue. We also load the file in memory, split into 500 lines chunks. If the chunks are too small, the mappers will receive too many messages, which makes the code go slow. If the chunks are too big, the job will not be split evenly among the mappers[5].</p>
<p><pre class="brush: ruby;">start = nil
values = Hash.new 0
linesToRead = input.size
reduceActor = actor do |message|
  linesToRead -= 1
  hash = message
  hash.each do |key, value|
    values[key] += value
  end
  if linesToRead == 0
    puts &quot;&gt;&gt; All over: Just to say we used any computed value: #{values['shakespeare']}&quot;
    finish = Time.now
    puts &quot;&gt;&gt; Total time: #{finish - start}s&quot;
    Akka::ActorRegistry.shutdownAll()
  end
end
</pre></p>
<p>The reducer actor is pretty straightforward. When all chunks are read, he shutdowns all actors and outputs the result and the time it took for the whole map-reduce chain to take place.</p>
<p><pre class="brush: ruby;">mapActorsSize = 2
mapActors = []
wordCount = WordCount.new
workStealer = AkkaDispatcher.workStealer 'mappers'
mapActorsSize.times do
  mapActor = actor do |message|
    reduceActor.sendOneWay wordCount.count message
  end
  mapActor.setDispatcher workStealer
  mapActors.push mapActor
end
</pre></p>
<p>The mappers delegate the actual work to an immutable <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/regular_word_count.rb">WordCount class</a>. The important part is the one that sets the same dispatcher on the actors. More on how this work on <a href="http://doc.akkasource.org/dispatchers-java#Dispatchers%20%28Java%29-Types%20of%20dispatchers-Work-stealing%20event-based">Akka&#8217;s documentation</a>.</p>
<p><pre class="brush: ruby;">
mapActor = mapActors.first
producer = actor do |message|
  for line in input
    mapActor.sendOneWay line
  end
end

allActors = [reduceActor, producer] + mapActors
allActors.each do |a|
  a.start
end
start = Time.now
producer.sendOneWay :start
</pre></p>
<p>These lines define the producer, start all actors, set the start time, and send the producer actor a message, which begins the map-reduce chain. It is important to note that the program&#8217;s main thread finishes on the last line. <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/await_done.rb">This example</a> shows how It is possible to make it wait for the result and then resume the main thread (it requires using the other types of message sending methods, thus I&#8217;ll not cover it in detail).</p>
<p><em>Results:</em> The <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/regular_word_count.rb">sequential version</a> runs on my machine (which has 2 cores) in about 4 seconds. This one with map-reduce actors take about 3 seconds, which yields a 25% improvement[6].</p>
<h4><span style="text-decoration:underline;"><strong><strong><strong><strong>Conclusion</strong></strong></strong></strong></span></h4>
<p>This post showed how it is easy to use Akka actors with JRuby and that they can easily enable thread-safe and easy to reason multicore programming. The <a href="http://akkasource.org/">Akka</a> project has many other tools to help with distributed/parallel programming, such as <a href="http://doc.akkasource.org/remote-actors-java">remote actors</a>, <a href="http://doc.akkasource.org/stm-java">software transactional memory</a>, and integrations with all sorts of persistence/queue systems. This post barely scratches the surface.</p>
<p>All the code on this blog post can be found on <a href="https://github.com/danielribeiro/RubyOnAkka/">github</a>, where all dependencies are easily available, and instructions on how to easily run the code. Give it a try, and see if you agree (<a href="http://codemonkeyism.com/actor-myths/?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+stephansblog+%28Code+Monkeyism+|+Stephans+Blog%29">or not</a>) with <a href="http://beust.com/weblog/2010/08/19/clojure-concurrency-and-silver-bullets/?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+beust%2FOtakuXml+%28Otaku%2C+Cedric%27s+weblog%29#comment-8472">others</a> that writing parallel code can be much easier and fun.</p>
<h4><span style="text-decoration:underline;"><strong><strong><strong><strong><strong><strong><strong><strong>Footnotes</strong></strong></strong></strong></strong></strong></strong></strong></span></h4>
<p>[1] As Daniel Spiewak showed it on his <em><a href="http://www.codecommit.com/blog/ruby/integrating-scala-into-jruby">Integrating Scala into JRuby</a></em> post.</p>
<p>[2] Incidentally Akka was started by <a href="http://jonasboner.com/">Jonas Bonér</a>, who is also one of the creators of  the java AOP tool <a href="http://aspectwerkz.codehaus.org/">AspectWerkz</a>, which is included in <a href="http://eclipse.org/aspectj/">Aspectj</a> nowadays.</p>
<p>[3] From a <a href="http://www.infoq.com/interviews/functional-langs">interview with</a> Joe Armstrong, the creator of Erlang:</p>
<p><em>Actually  it’s a kind of 180 degree turn because I wrote a blog article that said  &#8220;Why object-oriented programming is silly&#8221; or &#8220;Why it sucks&#8221;. I wrote  that years ago and I sort of believed that for years. Then, my thesis  supervisor, Seif Haridi, stopped me one day and he said &#8220;You’re wrong!  Erlang is object oriented!&#8221;</em></p>
<p>[4] In general, you need to create a <a href="http://doc.akkasource.org/untyped-actors-java#Actors%20%28Java%29--Creating%20Actors%20with%20non-default%20constructor">UntypedActorFactory</a> to pass arguments to the constructor, which we <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/akka.rb#L14">already do</a> (implicitly, using <a href="http://kenai.com/projects/jruby/pages/CallingJavaFromJRuby#Closure_conversion">JRuby&#8217;s closure to interface</a> coercion), but even then Ruby&#8217;s Actors <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/wont_work_if_class_new_is_not_redefined.rb">will not work</a>. This could be worked around by changing the Actors module and invoking another hook method that is not initialize.</p>
<p>[5] Thanks to the Akka committers Viktor Klang and Peter Veentjer for <a href="http://groups.google.com/group/akka-user/browse_thread/thread/d37d03b9f028f8df">the hint.</a></p>
<p>[6] This is not a real benchmark. Making a real one requires a <a href="http://news.ycombinator.com/item?id=1982844">lot more attention to details</a> like jvm warm-up, jiting from ruby to java, jiting on java bytecode, and so on.</p>
<br /> Tagged: <a href='http://metaphysicaldeveloper.wordpress.com/tag/actors/'>actors</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/akka/'>akka</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/concurrency/'>concurrency</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/ruby/'>Ruby</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/scala/'>scala</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/metaphysicaldeveloper.wordpress.com/300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/metaphysicaldeveloper.wordpress.com/300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/metaphysicaldeveloper.wordpress.com/300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/metaphysicaldeveloper.wordpress.com/300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/metaphysicaldeveloper.wordpress.com/300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/metaphysicaldeveloper.wordpress.com/300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/metaphysicaldeveloper.wordpress.com/300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/metaphysicaldeveloper.wordpress.com/300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/metaphysicaldeveloper.wordpress.com/300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/metaphysicaldeveloper.wordpress.com/300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/metaphysicaldeveloper.wordpress.com/300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/metaphysicaldeveloper.wordpress.com/300/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=300&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2010/12/16/high-level-concurrency-with-jruby-and-akka-actors/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>
	</item>
		<item>
		<title>RubyUnderscore: A bit of Arc and Scala in Ruby</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2010/10/31/rubyunderscore-a-bit-of-arc-and-scala-in-ruby/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2010/10/31/rubyunderscore-a-bit-of-arc-and-scala-in-ruby/#comments</comments>
		<pubDate>Mon, 01 Nov 2010 01:17:46 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Closures]]></category>
		<category><![CDATA[Implementation]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=271</guid>
		<description><![CDATA[A few months ago I&#8217;ve mentioned one thing that bothered me in ruby was &#8220;No way to create simple blocks&#8221;. This is in contrast to other languages, such as Scala, Clojure and Groovy&#8217;s underscore, percent and &#8220;it&#8221;, respectively, shortcut notations. There are other languages with equivalent mechanisms as well. Even newer languages like Coffeescript have [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=271&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A <a href="../../../../../2010/03/31/improving-ruby/">few months ago</a> I&#8217;ve mentioned one thing that bothered me in ruby was   <em>&#8220;</em><em>No way to create simple blocks&#8221;</em><em>. </em>This is in contrast to other languages, such as Scala, Clojure and Groovy&#8217;s underscore, percent and &#8220;it&#8221;, respectively, shortcut notations. There <a href="http://github.com/jashkenas/coffee-script/issues/issue/739/#issue/739">are other languages </a>with equivalent mechanisms as well. Even newer languages like <a href="http://jashkenas.github.com/coffee-script/">Coffeescript</a> have <a href="http://github.com/jashkenas/coffee-script/issues/issue/739/#comment_450208">considered</a> adding it. As James Iry <a href="http://james-iry.blogspot.com/2010/03/robert-fischer-finally-admits-that.html">mentioned</a>, such constructs are in fact related to <a href="http://okmij.org/ftp/gengo/#Scala-trace">delimited continuations</a>.</p>
<p>However ruby has <a href="http://en.wikipedia.org/wiki/Abstract_syntax_tree">Syntax Tree</a> manipulation (via <a href="http://parsetree.rubyforge.org/">Parse Tree</a> gem). Using it I created the <a href="http://github.com/danielribeiro/RubyUnderscore">RubyUnderscore</a> project, which brings this ruby, using the underscore symbol (just like <a href="http://www.scala-lang.org/">Scala</a> and <a href="http://arclanguage.org/">Arc</a>). With it, it is possible to refactor the following:</p>
<pre><strong><code>    classes.reject { |c| c.subclasses.include?(Enumerable) }</code>
<code>    dates.select { |d| d.greater_than(old_date) }</code>
<code>    collection.map { |x| x.invoke }</code></strong></pre>
<p>into:</p>
<pre><strong><code>    classes.reject _.subclasses.include? Enumerable</code>
<code>    dates.select _.greater_than old_date</code>
<code>    collection.map _.invoke</code></strong></pre>
<p>The last case can also use symbol to proc coercion (appending &amp; to symbol):</p>
<pre><strong><code>     collection.map &amp;:invoke</code></strong></pre>
<p>However, the proc coercion is not flexible enough to allow arguments or invoke a method chain. Which I think brings a small increase in readability and <a href="../../../../../wp-admin/post.php?post=46&amp;action=edit">code quality</a>, not to mention that by making closures easier to declare, it fosters them to be used more. I find this to be a <a href="../../../../../wp-admin/post.php?post=64&amp;action=edit">good thing</a>, specially when you start to refactor your loops into <a href="http://ruby-doc.org/core-1.8.7/classes/Enumerable.html#M001146">maps</a>, <a href="http://ruby-doc.org/core-1.8.7/classes/Enumerable.html#M001143">selects</a>, <a href="http://ruby-doc.org/core-1.8.7/classes/Enumerable.html#M001144">rejects</a>, <a href="http://ruby-doc.org/core-1.8.7/classes/Enumerable.html#M001150">group_bys</a> and <a href="http://ruby-doc.org/core-1.8.7/classes/Enumerable.html#M001148">reduces</a></p>
<p>This also highlights another issue I mentioned in <a href="../../../../../2010/03/31/improving-ruby/">Improving Ruby</a>: that Syntax Tree manipulation is too important to be supported only on MRI, and not throughout the implementations, like JRuby and Rubinius. Python has this built in into its standard library (through <a href="http://docs.python.org/library/ast.html">ast</a> module and <a href="http://docs.python.org/library/inspect.html#inspect.getsource">inspect.getsource</a>), and Lisp can also do syntax tree manipulation with its <a href="http://stackoverflow.com/questions/1988/how-far-can-lisp-macros-go">macro system</a>. The importance of such capability was <a href="http://www.paulgraham.com/ilc03.html">mentioned</a> by <a href="../../../../../2010/04/30/scrapbooking-startup-essays/">Paul Graham</a> (one of the creators of Arc, which is a dialect of Lisp):</p>
<p><em>Letting people rewrite your language is a good idea. You, as the language designer, can&#8217;t possibly anticipate all the things programmers are going to want to do with it. To the extent they can rewrite the language, you don&#8217;t have to.</em></p>
<p>However, syntax tree manipulation in ruby is not only unsupported in most implementations, but it is also poorly documented (even though <a href="http://www.postrank.com/">PostRank&#8217;s</a> founder <a href="http://twitter.com/#%21/igrigorik">Ilya Grigorik</a>&#8216;s post on the <a href="http://www.igvita.com/2008/12/11/ruby-ast-for-fun-and-profit/?utm_source=feedburner&amp;utm_campaign=Feed:+igvita+%28igvita.com%29&amp;utm_content=feed">subject is a very good introduction</a>) and a bit awkward to use: the <a href="http://en.wikipedia.org/wiki/Visitor_pattern">visitor</a> from <a href="http://rubygems.org/gems/sexp_processor">sexp-processor gem</a> embraces side effect (mutating all the tree nodes while processing them) and the tree nodes are just arrays, unlike Python&#8217;s modules where there is a class for every node type. It is important to note that if you are willing to pre-process your ruby code, you can use <a href="http://seattlerb.rubyforge.org/ruby2ruby/">ruby2ruby</a> to generate the equivalent and regular ruby code, which will work all over.</p>
<p>These techniques are expected to be fixed as more people realize the gains they bring, and these improvements find their way into YARV and eventually other ruby implementations. Ruby is a very nice, clean, productive and elegant language, and it would be shame if we stopped making it even better.</p>
<br /> Tagged: <a href='http://metaphysicaldeveloper.wordpress.com/tag/closures/'>Closures</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/implementation/'>Implementation</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/ruby/'>Ruby</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/scala/'>scala</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/metaphysicaldeveloper.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/metaphysicaldeveloper.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/metaphysicaldeveloper.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/metaphysicaldeveloper.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/metaphysicaldeveloper.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/metaphysicaldeveloper.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/metaphysicaldeveloper.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/metaphysicaldeveloper.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/metaphysicaldeveloper.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/metaphysicaldeveloper.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/metaphysicaldeveloper.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/metaphysicaldeveloper.wordpress.com/271/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=271&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2010/10/31/rubyunderscore-a-bit-of-arc-and-scala-in-ruby/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>
	</item>
		<item>
		<title>The Issue with Static Typing</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2010/06/30/the-issue-with-static-typing/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2010/06/30/the-issue-with-static-typing/#comments</comments>
		<pubDate>Thu, 01 Jul 2010 02:53:07 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[Languages]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=212</guid>
		<description><![CDATA[&#8220;Shouldn&#8217;t we use Scala?&#8221; is a recurring question my peers make me. I think it is fair, since I have advocated in the past that Scala has a lot of strong points compared to Java. Furthermore, this question is usually made in contrast to dynamic languages, usually Ruby or Python. Since I don&#8217;t want to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=212&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>&#8220;Shouldn&#8217;t we use Scala?&#8221; is a recurring question my peers make me. I think it is fair, since I have <a href="http://metaphysicaldeveloper.wordpress.com/2009/07/29/scala-the-successor-to-the-throne/">advocated in the past </a>that Scala has a lot of strong points compared to Java. Furthermore, this question is usually made in contrast to dynamic languages, usually Ruby or Python.</p>
<p>Since I don&#8217;t want to discuss that common confusion of  strong with static typing, I&#8217;ll try to be very clear about what I&#8217;m talking about. By static type I mean that the types of all data must be known at <em>compile time</em>. By dynamic I mean that the types may not be known until runtime. Of course, this ignores languages that have mixed typing, such as Groovy, Objective-C and C#4.0 (as it includes the <a href="http://stackoverflow.com/questions/244302/what-do-you-think-of-the-new-c-40-dynamic-keyword">dynamic keyword</a>), but for argument&#8217;s sake, these can be ignored as the issues of static typing will apply to these as well whenever you are using it, and will not whenever you aren&#8217;t. The common examples of languages are Smalltalk, Clojure, Erlang, Ruby, Python, Lisp, Lua, Javascript, for dynamically typed, and Java, Haskell, Scala, C#, C++ for statically typed.</p>
<p>Statically typed languages have as usual <em>claimed</em> benefits that they are faster than dynamic languages, their types provide documentation of the methods and functions, static analysis tools can be more comprehensive and yield better results, and automated refactoring is a lot easier to accomplish and can also give better results. All of these reflect more the current state of implementation and tooling of such languages than of intrinsic property of the type  of the language. Steve Yegge <a href="http://steve-yegge.blogspot.com/2008/05/dynamic-languages-strike-back.html">has argued</a> this about the speed property, but one can argue for dynamic language that its tooling could use type information from runtime sources, such as unit-testing, to yield similar results .</p>
<p>But some hidden complexities take place when using static typing, which may overthrow any possible benefits coming from it:</p>
<ul>
<li>The biggest one is <em>type coupling</em>. For instance, in dynamic languages, renaming an interface is trivial as most interfaces are not even declared, just  documented (such as &#8220;this must implement less than&#8221;). <a href="http://codemonkeyism.com/scala-goodness-structural-typing/">Structural typing</a> can ease this, so can <a href="http://dcsobral.blogspot.com/2010/06/implicit-tricks-type-class-pattern.html">type classes</a>. However, even languages that support these can have problems with other refactorings, such as adding methods to an interface. Paul Graham comments about this a little (on the essay <a href="http://paulgraham.com/hp.html">Hackers and Painters</a>):</li>
</ul>
<blockquote><p>Everyone by now presumably knows about the danger of premature optimization. I think we should be just as worried about premature design&#8211; deciding too early what a program should do.</p>
<p>The right tools can help us avoid this danger. A good programming language should, like oil paint, make it easy to change your mind. Dynamic typing is a win here because you <strong>don&#8217;t have to commit to specific data representations up front</strong>. But the key to flexibility, I think, is to make the language very <a href="http://www.paulgraham.com/power.html" target="_blank">abstract</a>.</p></blockquote>
<ul>
<li><em>Some DSLs can&#8217;t be built</em>. A common example is the <a href="http://www.codecommit.com/blog/ruby/xmlbuilder-a-ruby-dsl-case-study">XML DSL</a>. This is because you can&#8217;t have in a pure statically typed language a type that accepts any single method call, returning any single possible return value, given any amount of any arguments of any type. In fact, if you do have this type, you in fact have the <em>dynamic</em> type from C#. Dynamic languages usually support this through a mechanism called <a href="http://www.google.com/url?sa=t&amp;source=web&amp;cd=2&amp;ved=0CBsQFjAB&amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.91.1021%26rep%3Drep1%26type%3Dpdf&amp;rct=j&amp;q=method+lookup+alteration+and+interception&amp;ei=ZSEsTMTYC4KJuAfw2p3CCQ&amp;usg=AFQjCNH7dktUqD_4vSjR5aHidE9U4Y3sIg&amp;sig2=bHOpRznFWe0WqxTJxx9D9w">method lookup  alteration and interception</a>, such as those provided by Smalltalk’s <em>doesNotUnderstand, </em>Ruby’s <em>missing_method</em> and Python&#8217;s <em>__gettattr__</em> method.</li>
<li><em>Natural complexity</em>. By this I mean that every statically typed languages is a proper superset of a dynamic language of itself. This is easy to see from the theory behind types, as the untyped lambda calculus is just the typed lambda calculus with one type (the brave ones can find more about this on <a href="http://math.ucr.edu/home/baez/rosetta.pdf" target="_blank">Physics,  Topology, Logic and Computation A Rosetta Stone</a>).</li>
<li><em>False sense of safety</em>. The types do not guarantee that the implementations maintain the invariants of a type (such as <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle">those described by Baraba Liskov</a>). The common example is a <a href="http://java.sun.com/javase/6/docs/api/">comparator interface</a> in Java. Just because a class implements the interface, it doesn&#8217;t mean that the compare method is transitive, as required by the documentation. James Iry <a href="http://james-iry.blogspot.com/2010/05/types-la-chart.html">recently commented</a> on languages with more complex type systems (he actually said a lot more about type systems in general), that contain theorem provers in their compilers, such <a href="http://en.wikipedia.org/wiki/Agda_%28theorem_prover%29">Agda</a> and <a href="http://en.wikipedia.org/wiki/Epigram_%28programming_language%29">Epigram</a>, which can solve this issue. However such languages have other limitations, such as not being <a href="http://en.wikipedia.org/wiki/Turing_Complete">Turing Complete</a>. This essentially means that testing practices are still as needed as for static languages (even if you have theorem provers, you cannot be sure without some form of acceptance tests that the problem you are trying to solve is actually the one the customer had in his mind).</li>
<li><em><a href="http://www.scala-lang.org/node/129">Type variances</a></em>. This is actually two problems: if your languages does not support them, you have to fall back to <a href="http://en.wikipedia.org/wiki/Cast_%28computer_science%29">type casting</a>, which actually violates type-saftey and static typing in general. If your language supports it, you have to know one more concept, and when to apply it. It may not be always clear when a type should be co-variant or contravariant. This is further complicated by the fact that types with side effects (such as mutable objects) have special rules about this (further about this can be found under <em><a href="http://programming-scala.labs.oreilly.com/ch12.html">Variance of Mutable Types</a></em>, from Programming Scala). Also this concept is so common that functions are naturally covariant on the return value and contravariant on the parameters. Scala&#8217;s <a href="http://www.scala-lang.org/docu/files/api/scala/Function2.html">two argument function</a> documentation shows this explicitly.</li>
</ul>
<p>The last two issues are very diminished for languages without <a href="http://en.wikipedia.org/wiki/Subtype">subtyping</a>, but these have deeper problems as, in order to relinquish subtyping, you also have to give up on any possibility of code reuse possibility from <a href="http://en.wikipedia.org/wiki/Ad-hoc_polymorphism">ad-hoc polymorphism</a>.</p>
<p>It might seem that some points were left out, but these are usually the problem of a particular language, which are commonly and mistakenly considered to be a problem of static typing in general:</p>
<ul>
<li><em>Lack of metaprogramming support</em>.  Of course C++ has templates, which means that most people know that this is false for all statically typed languages. However, a variant of this issue is: <em>type safe safe metaprogramming</em>. This is also not true. Haskell, for instance, has a <a href="http://intoverflow.wordpress.com/2010/06/30/haskell-features-id-like-to-see-in-other-languages/">type-safe macro system</a>. Note that you cannot make type-safe runtime metaprogramming in general. For instance: even though some languages allow you to create interfaces that do not exist on compile time, the only way to invoke methods from these is through non type-safe ways (such as reflection).</li>
<li><em>Verbosity</em>. Scala is the canonical counter-example (Scala can be as terse as Clojure <a href="http://news.ycombinator.com/item?id=1467153">in some ways</a>). The more type-inference you have, the less type annotation you have to write. This doesn&#8217;t necessarily make reading it easier, but IDEs can help here. On the other hand, it will never be harder to read than dynamic languages.</li>
</ul>
<p>Going back to the question that originated this discussion: static types can come in handy, and they do have better tools these days. But they do bring complexities way beyond having to type a few extra characters. And these should not be taken lightly when considering to express code in a statically typed language.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/212/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/212/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/metaphysicaldeveloper.wordpress.com/212/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/metaphysicaldeveloper.wordpress.com/212/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/metaphysicaldeveloper.wordpress.com/212/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/metaphysicaldeveloper.wordpress.com/212/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/metaphysicaldeveloper.wordpress.com/212/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/metaphysicaldeveloper.wordpress.com/212/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/metaphysicaldeveloper.wordpress.com/212/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/metaphysicaldeveloper.wordpress.com/212/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/metaphysicaldeveloper.wordpress.com/212/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/metaphysicaldeveloper.wordpress.com/212/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/metaphysicaldeveloper.wordpress.com/212/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/metaphysicaldeveloper.wordpress.com/212/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=212&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2010/06/30/the-issue-with-static-typing/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>
	</item>
		<item>
		<title>Scrapbooking Startup Essays</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2010/04/30/scrapbooking-startup-essays/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2010/04/30/scrapbooking-startup-essays/#comments</comments>
		<pubDate>Sat, 01 May 2010 02:50:46 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Startups]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=190</guid>
		<description><![CDATA[I have been talking a bit about startups recently. In these conversations it is common that I bring up some essay from Paul Graham, as he wrote a lot of very insightful articles on the topic (not to mention invested in). However, there are too many good essays, and I usually have a hard time remembering [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=190&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I have been talking a bit about startups recently. In these conversations it is common that I bring up some <a href="http://paulgraham.com/articles.html">essay</a> from Paul Graham, as he wrote a lot of very insightful articles on the topic (not to mention <a href="http://ycombinator.com/">invested</a> in). However, there are too many good essays, and I usually have a hard time remembering the highlights among all of them, or pointing them to friends. Therefore I have assembled the parts that I personally found to be the most insightful, clever, intriguing  and/or just plain controversial.</p>
<p><strong>Note:</strong> I have published a <a href="https://addons.mozilla.org/pt-BR/firefox/addon/748">Greasemonkey</a> script called <em><a href="http://userscripts.org/scripts/show/75633">Paul Graham Topics</a></em> that adds a topic sidebar on the essays, to make it easier to read them.</p>
<p>For those who dislike Greasemonkey, or just wanna see if it is worth installing it, <a href="http://paulgrahamsidebar.heroku.com/">I&#8217;ve uploaded here </a>a <a href="http://www.sinatrarb.com/">Sinatra</a> app on Heroku (which incidentally was <a href="http://techcrunch.com/2008/02/07/heroku-lifts-ruby-on-rails-development-to-the-cloud/">funded by Paul Graham</a>) that adds the script. The source of the project can be found <a href="http://github.com/danielribeiro/PaulGrahamSideBar">here</a>.</p>
<p><strong>Edit</strong> (24/Jun/2010): Added Paul Graham&#8217;s definition of startup  (from How To Make Wealth), just to contrast with <a href="http://www.startuplessonslearned.com/2010/06/what-is-startup.html">this one</a> given by <a href="http://twitter.com/ericries">Eric Ries</a> (who is getting a lot of attention lately with his Lean Startup movement and <a href="http://www.startuplessonslearned.com/2010/05/thank-you.html">Startup Lessons Learned</a> conference): &#8220;<em>A startup is a human institution designed to deliver a new product or service under conditions of extreme uncertainty.&#8221;</em></p>
<p><em>Disclaimer:</em> I do not claim ownership of any of the text below.</p>
<p><strong><a href="http://paulgraham.com/ideas.html">Ideas for Startups</a></strong><br />
If 98% of the time success means getting bought, why not be open about it?</p>
<p>Perhaps letting your mind wander is like doodling with ideas. You have certain mental gestures you&#8217;ve learned in your work, and when you&#8217;re not paying attention, you keep making these same gestures, but somewhat randomly. In effect, you call the same functions on random arguments. That&#8217;s what a metaphor is: a function applied to an argument of the wrong type.</p>
<p><strong><a href="http://www.paulgraham.com/wealth.html">How to Make Wealth</a></strong><br />
Startups usually involve technology, so much so that the phrase &#8220;high-tech startup&#8221; is almost redundant. A startup is a small company that takes on a hard technical problem.</p>
<p>(&#8230;) it is, as Edison said, one percent inspiration and ninety-nine percent perspiration.</p>
<p>One way to put up barriers to entry is through patents. But patents may not provide much protection. Competitors commonly find ways to work around a patent. And if they can&#8217;t, they may simply violate it and invite you to sue them. A big company is not afraid to be sued; it&#8217;s an everyday thing for them. They&#8217;ll make sure that suing them is expensive and takes a long time. Ever heard of Philo Farnsworth? He invented television. The reason you&#8217;ve never heard of him is that his company was not the one to make money from it. The company that did was RCA, and Farnsworth&#8217;s reward for his efforts was a decade of patent litigation.</p>
<p>The mere possibility of being interrupted deters hackers from starting hard projects. This is why they tend to work late at night, and why it&#8217;s next to impossible to write great software in a cubicle (except late at night).</p>
<p>Big companies can develop technology. They just can&#8217;t do it quickly. Their size makes them slow and prevents them from rewarding employees for the extraordinary effort required. So in practice big companies only get to develop technology in fields where large capital requirements prevent startups from competing with them, like microprocessors, power plants, or passenger aircraft. And even in those fields they depend heavily on startups for components and ideas.</p>
<p><strong><a href="http://paulgraham.com/mit.html">A Student&#8217;s Guide to Startups</a></strong><br />
That is one of the most distinctive differences between school and the real world: there is no reward for putting in a good effort.</p>
<p>One of the things employers expect from someone with &#8220;work experience&#8221; is the ability to get things done, with no excuses</p>
<p>So class projects are mostly about implementation, which is the least of your problems in a startup.</p>
<p><strong><a href="http://www.paulgraham.com/really.html">What Startups Are Really Like</a></strong></p>
<p>If ideas really were the key, a competitor with the same idea would be a real threat. But it&#8217;s usually execution that matters.</p>
<p><strong><a href="http://paulgraham.com/start.html">How to Start a Startup</a></strong><br />
No matter what kind of startup you start, it will probably be a stretch for you, the founders, to understand what users want. The only kind of software you can build without studying users is the sort for which you are the typical user. But this is just the kind that tends to be open source.</p>
<p>It&#8217;s easier to make an inexpensive product more powerful than to make a powerful product cheaper</p>
<p><strong><a href="http://paulgraham.com/bronze.html">Why Smart People Have Bad Ideas</a></strong><br />
Work people like doesn&#8217;t pay well, for reasons of supply and demand. The most extreme case is developing programming languages, which doesn&#8217;t pay at all, because people like it so much they do it for free.</p>
<p><strong><a href="http://www.paulgraham.com/notnot.html">Why to Not Not Start a Startup</a></strong><br />
That&#8217;s ultimately what drives us to work on Y Combinator. We want to make money, if only so we don&#8217;t have to stop doing it, but that&#8217;s not the main goal. There have only been a handful of these great economic shifts in human history. It would be an amazing hack to make one happen faster.</p>
<p>It&#8217;s exciting to think we may be on the cusp of another shift like the one from farming to manufacturing. That&#8217;s why I care about startups. Startups aren&#8217;t interesting just because they&#8217;re a way to make a lot of money. I couldn&#8217;t care less about other ways to do that, like speculating in securities. At most those are interesting the way puzzles are. There&#8217;s more going on with startups. They may represent one of those rare, historic shifts in the way wealth is created.</p>
<p><strong><a href="http://www.paulgraham.com/hp.html">Hackers and Painters</a></strong><br />
I&#8217;ve never liked the term &#8220;computer science.&#8221; The main reason I don&#8217;t like it is that there&#8217;s no such thing. Computer science is a grab bag of tenuously related areas thrown together by an accident of history, like Yugoslavia. At one end you have people who are really mathematicians, but call what they&#8217;re doing computer science so they can get DARPA grants. In the middle you have people working on something like the natural history of computers&#8211; studying the behavior of algorithms for routing data through networks, for example. And then at the other extreme you have the hackers, who are trying to write interesting software, and for whom computers are just a medium of expression, as concrete is for architects or paint for painters. It&#8217;s as if mathematicians, physicists, and architects all had to be in the same department.</p>
<p><strong><a href="http://www.paulgraham.com/gh.html">Great Hackers</a></strong><br />
After software, the most important tool to a hacker is probably his office. Big companies think the function of office space is to express rank. But hackers use their offices for more than that: they use their office as a place to think in. And if you&#8217;re a technology company, their thoughts are your product. So making hackers work in a noisy, distracting environment is like having a paint factory where the air is full of soot.</p>
<p><strong><a href="http://www.paulgraham.com/power.html">Succinctness is Power</a></strong><br />
I wrote about this in On Lisp. A complex macro may have to save many times its own length to be justified. If writing some hairy macro could save you ten lines of code every time you use it, and the macro is itself ten lines of code, then you get a net saving in lines if you use it more than twice. But that could still be a bad move, because macro definitions are harder to read than ordinary code. You might have to use the macro ten or twenty times before it yielded a net improvement in readability.</p>
<p><strong><a href="http://www.paulgraham.com/webstartups.html">The Future of Web Startups</a></strong><br />
Is seed funding not merely national, but international? Interesting question. There are signs it may be. We&#8217;ve had an ongoing stream of founders from outside the US, and they tend to do particularly well, because they&#8217;re all people who were so determined to succeed that they were willing to move to another country to do it.</p>
<p><strong><a href="http://www.paulgraham.com/knuth.html">Knuth: Computer Programming as an Art</a></strong><br />
Language designers also have an obligation to provide languages that encourage good style, since we all know that style is strongly influenced by the language in which it is expressed. The present surge of interest in structured programming has revealed that none of our existing languages is really ideal for dealing with program and data structure, nor is it clear what an ideal language should be. Therefore I look forward to many careful experiments in language design during the next few years.</p>
<p>In this sense we should continually be striving to transform every art into a science: in the process, we advance the art.</p>
<p>&#8220;The science without the art is likely to be ineffective; the art without the science is certain to be inaccurate.&#8221;</p>
<p><strong><a href="http://www.paulgraham.com/opensource.html">What Business Can Learn from Open Source</a></strong><br />
There&#8217;s a name for people who work for the love of it: amateurs. The word now has such bad connotations that we forget its etymology, though it&#8217;s staring us in the face. &#8220;Amateur&#8221; was originally rather a complimentary word. But the thing to be in the twentieth century was professional, which amateurs, by definition, are not.</p>
<p>As in software, when professionals produce such crap, it&#8217;s not surprising if amateurs can do better. Live by the channel, die by the channel: if you depend on an oligopoly, you sink into bad habits that are hard to overcome when you suddenly get competition.</p>
<p><strong><a href="http://www.paulgraham.com/good.html">Be Good</a></strong><br />
You can see how there would be. When you&#8217;re small, you can&#8217;t bully customers, so you have to charm them. Whereas when you&#8217;re big you can maltreat them at will, and you tend to, because it&#8217;s easier than satisfying them. You grow big by being nice, but you can stay big by being mean.</p>
<p>You get away with it till the underlying conditions change, and then all your victims escape. So &#8220;Don&#8217;t be evil&#8221; may be the most valuable thing Paul Buchheit made for Google, because it may turn out to be an elixir of corporate youth. I&#8217;m sure they find it constraining, but think how valuable it will be if it saves them from lapsing into the fatal laziness that afflicted Microsoft and IBM.</p>
<p>From what we&#8217;ve seen, being good seems to help startups in three ways: it improves their morale, it makes other people want to help them, and above all, it helps them be decisive.</p>
<p><strong><a href="http://www.paulgraham.com/raq.html">Rarely-Asked Questions</a></strong><br />
Couldn&#8217;t you add something equivalent to Lisp macros to languages like Perl or Python?<br />
(&#8230;) But it would be hard to do that without creating a notation for parse trees; and once you do, your language has become a skin on Lisp</p>
<p><strong><a href="http://www.paulgraham.com/whyyc.html">Why YC</a></strong><br />
The real reason we started Y Combinator is neither selfish nor virtuous. We didn&#8217;t start it mainly to make money; we have no idea what our average returns might be, and won&#8217;t know for years. Nor did we start YC mainly to help out young would-be founders, though we do like the idea, and comfort ourselves occasionally with the thought that if all our investments tank, we will thus have been doing something unselfish. (It&#8217;s oddly nondeterministic.)</p>
<p><strong><a href="http://www.paulgraham.com/startupmistakes.html">The 18 Mistakes That Kill Startups</a></strong><br />
The reason we tell founders not to worry about the business model initially is that making something people want is so much harder.<br />
<strong> </strong></p>
<p><strong><a href="http://www.paulgraham.com/marginal.html">The Power of the Marginal</a></strong><br />
I think that&#8217;s one reason big companies are so often blindsided by startups. People at big companies don&#8217;t realize the extent to which they live in an environment that is one large, ongoing test for the wrong qualities.</p>
<p>The eminent, on the other hand, are weighed down by their eminence. Eminence is like a suit: it impresses the wrong people, and it constrains the wearer.</p>
<p>So if you&#8217;re an outsider you should actively seek out contrarian projects. Instead of working on things the eminent have made prestigious, work on things that could steal that prestige.</p>
<p>If you really want to score big, the place to focus is the margin of the margin: the territories only recently captured from the insiders. That&#8217;s where you&#8217;ll find the juiciest projects still undone, either because they seemed too risky, or simply because there were too few insiders to explore everything.</p>
<p>So that, I think, should be the highest goal for the marginal. Be inappropriate. When you hear people saying that, you&#8217;re golden. And they, incidentally, are busted.</p>
<p><strong><a href="http://paulgraham.com/langdes.html">Five Questions about Language Design</a></strong><br />
(&#8230;) designing programming languages is like designing chairs: it&#8217;s all about dealing with human weaknesses.</p>
<p>If you look at the history of programming languages, a lot of the best ones were languages designed for their own authors to use, and a lot of the worst ones were designed for other people to use.</p>
<p>When I first learned Lisp, what I liked most about it was that it considered me an equal partner. In the other languages I had learned up till then, there was the language and there was my program, written in the language, and the two were very separate. But in Lisp the functions and macros I wrote were just like those that made up the language itself. I could rewrite the language if I wanted. It had the same appeal as open-source software.</p>
<p>Another thing that might turn out to be useful for server based software, surprisingly, is continuations. In Web-based software you can use something like continuation-passing style to get the effect of subroutines in the inherently stateless world of a Web session. Maybe it would be worthwhile having actual continuations, if it was not too expensive.</p>
<p>It&#8217;s traditional to think of syntax and semantics as being completely separate. This will sound shocking, but it may be that they aren&#8217;t. I think that what you want in your language may be related to how you express it.</p>
<p>Is it necessary to take risks to design a good language though? Many people might suspect that language design is something where you should stick fairly close to the conventional wisdom. I bet this isn&#8217;t true. In everything else people do, reward is proportionate to risk. Why should language design be any different?</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/metaphysicaldeveloper.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/metaphysicaldeveloper.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/metaphysicaldeveloper.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/metaphysicaldeveloper.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/metaphysicaldeveloper.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/metaphysicaldeveloper.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/metaphysicaldeveloper.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/metaphysicaldeveloper.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/metaphysicaldeveloper.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/metaphysicaldeveloper.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/metaphysicaldeveloper.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/metaphysicaldeveloper.wordpress.com/190/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=190&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2010/04/30/scrapbooking-startup-essays/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>
	</item>
		<item>
		<title>Improving Ruby</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2010/03/31/improving-ruby/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2010/03/31/improving-ruby/#comments</comments>
		<pubDate>Thu, 01 Apr 2010 02:45:20 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[Functional]]></category>
		<category><![CDATA[future]]></category>
		<category><![CDATA[Opinion]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[Smalltalk]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/2010/03/31/improving-ruby/</guid>
		<description><![CDATA[Some may say Ruby is a bad rip-off of Lisp or Smalltalk, and I admit that. But it is nicer to ordinary people. &#8211; Yukihiro &#8220;Matz&#8221; Matsumoto, LL2 When I heard the Smalltalk traits of Ruby, I was intrigued. When I learned more, I enjoyed Ruby&#8217;s similarities with one of the most beautiful and powerful [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=149&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<blockquote><p><em>Some may say Ruby is a bad rip-off of Lisp or   Smalltalk, and I admit that. But it is nicer to ordinary people.</em></p>
<p>&#8211; <a href="http://en.wikipedia.org/wiki/Yukihiro_Matsumoto">Yukihiro  &#8220;Matz&#8221;  Matsumoto</a>, <a href="http://www.paulgraham.com/quotes.html">LL2</a></p></blockquote>
<p>When I heard the Smalltalk traits of Ruby, I was  intrigued. When I learned more, I enjoyed Ruby&#8217;s similarities with one of  the most beautiful and powerful languages I&#8217;ve known. As I dug deeper, I  enjoyed more of its wonderful metaprogramming abilities, which makes  Ruby&#8217;s classes a lot more dynamic and easy to declare than Smalltalk&#8217;s. After  reading <a href="http://lambda-the-ultimate.org/node/2606">this</a> in-depth comparison of both, and Kent Beck&#8217;s <a href="http://www.threeriversinstitute.org/blog/?p=466">article</a> on  the incompatibilities of Smalltalk&#8217;s VM implementations, I realized that I  was generally more in favor of Ruby than Smalltalk (even though I fear  that <a href="http://www.youtube.com/watch?v=YX3iRjKj7C0">What  Killed Smalltalk Could Kill Ruby, Too</a>).</p>
<p>But Ruby is not perfect. In all fairness, its creator <a href="http://www.artima.com/intv/ruby.html">claims that</a><em> it&#8217;s just plain impossible to design a perfect language</em>. But I do  believe it could be a bit better. People do point out some <a href="http://beust.com/weblog/2003/10/28/flaws-in-ruby/">controversial  rough edges</a>, but these seem a bit trifle when compared to what  really bothers me:</p>
<ul>
<li><a href="http://debasishg.blogspot.com/2008/02/why-i-like-scalas-lexically-scoped-open.html">No  scoped open classes</a>. It is an issue that is actually being considered to  be solved on 2.0 (and there are <a href="http://gist.github.com/358467">some branches</a> of ruby that enable it), but, for the time being, there is no way to make the  changes made by opening an existing class only apply to objects while  being used on the a lexical scope. This is not the same as adding and  removing the changes as, in this case, calls that fall out of scope  (such as to another module or file) still see the changes. It would be  nice to have both ways of open classes: scoped and not scoped.</li>
<li>Method  arguments do not interleave with the method&#8217;s name (like in  Smalltalk).  Example: Instead of calling: <em>File.fnmatch(&#8216;*&#8217;,   &#8216;/&#8217;,   File::FNM_PATHNAME)</em> you&#8217;d be to call it like: <em>File.fn match:  &#8216;*&#8217;  path: &#8216;/&#8217; flags: File::FNM_PATHNAME</em>.  This seems weird, but it  is a  very powerful feature that allows method invocation to be  descriptive,  similar to <a href="http://diveintopython.org/power_of_introspection/optional_arguments.html">Python&#8217;s   named arguments</a> or even <a href="http://deepfall.blogspot.com/2008/08/named-parameters-in-ruby.html">Ruby&#8217;s   named arguments</a> with a hash. On the other hand it has a cleaner   syntax than the former, and does not require checking hash keys as the   later (the later is still useful for methods that want to receive an   arbitrary list of named arguments). It would change a bit of the syntax of   method_missing and how to deal with varargs and blocks for each   parameter, but these can be dealt with as Scala does with its <a href="http://www.scala-lang.org/node/4871">parameter lists</a>.</li>
<li>There is no method called <em>()</em>. Procs (who are  the obvious beneficiaries of such change ) use the method <em>call</em>,  but one could be an alias to the other. There would be a mild ambiguity  here, when you call the function that was just returned. For instance,  imagine <em>func</em> is a method that receives no arguments and returns a function (that  is: an object that implements the <em>()</em> method) wich also receives  no arguments. Then <em>func()</em> could mean 1. call func, and 2. call  the function returned by func. I am aware this is kinda of a <a href="http://talklikeaduck.denhaven2.com/2010/03">sensitive</a> <a href="http://yehudakatz.com/2010/02/21/ruby-is-not-a-callable-oriented-language/">topic</a>, but the Scala approach to this issue is very  simple: func and func() are the same (provided func can be called with no  parenthesis). If you want to call the returned function in the same  expression, use <em>func()()</em>. With the alias, you&#8217;d be able to call  it like <em>func.call()</em> , <em>func().call()</em><em> </em>or<em> </em>even<em> func.call<br />
</em></li>
<li>No  way to create simple blocks. It would be nice to have something similar to  Scala&#8217;s <a href="http://james-iry.blogspot.com/2010/03/robert-fischer-finally-admits-that.html"><em>underscore</em></a> or Groovy&#8217;s <em>it</em>, which allows method  invocations like: <em>collection.map(get_square_of(_))</em> in Scala  and <em>collection.map(get_square_of(it))</em> in Groovy. Ruby&#8217;s symbol  coercion to proc (<em>&amp;:method</em>) does not really work on  anything besides methods of the arguments of the block.</li>
<li>Difficulties  of composing <a href="http://www.nach-vorne.de/2007/3/18/list-of-callback-methods/">callback  methods</a>. You could be sure to always invoke <em>super</em> on  them, and even meta-program all the classes/objects that do not do such thing.  However, it is not easy to actually see which methods will be called, or  even manipulate/re-prioritize the blocks of code on runtime (kinda like  a <a href="http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">Chain  of Responsibility</a>), which can be very bad, as these methods can modify a lot of behaviour throughout the Object Space.</li>
<li>The reflection API could be more thorough. For  instance, you can&#8217;t get the source code of a method/class, etc (as you  can in <a href="http://docs.python.org/library/inspect.html#inspect.getsource">Python</a>).   You can use <a href="http://parsetree.rubyforge.org/">Parse  Tree</a> and <a href="http://seattlerb.rubyforge.org/ruby2ruby/">Ruby2Ruby</a> to do it,  but Parse Tree is not portable (<a href="http://blog.zenspider.com/2009/04/parsetree-eol.html">does not  even work on ruby 1.9</a>) and the output can be formated differently  than the actual source code (which can be critical on DSLs). Also,  methods added do not have information on which line of code they were  added (which is less important when adding methods the recommended way:  extending/including Modules), and properties created with class methods  (such as those created by <em>attr_reader</em>, or <a href="http://www.mongodb.org/display/DOCS/MongoDB+Data+Modeling+and+Rails#MongoDBDataModelingandRails-ModelingStories">some</a> <a href="http://github.com/NZKoz/cassandra_object"> other</a> libraries equivalents) can&#8217;t be discovered on runtime (they  are like any other method, with no other meta-data whatsoever). Ruby also  seems to be missing some helper methods, such as <a href="http://ruby-metaprogramming.rubylearning.com/html/seeingMetaclassesClearly.html">#metaclass</a>.</li>
<li>No support for immutability. This is kinda nitpicking,  but using recursive freeze (as noted by <a href="http://ruby.dzone.com/videos/better-ruby-through-functional">Dean  Wampler</a>) is not really practical (as it is really slow). Neither does  it encompass immutable local variables. This is not only useful for  concurrency and functional programming issues, but is also useful when  writing code that is side-effect free so that it is easier to reason about.</li>
<li>The return value of a <em>setter</em> method (that is:  one that ends with the equals symbol) is the argument, not the return  value of the method. This is an issue that matters more when using  immutable objects, as the only way for them to <em>&#8220;mutate&#8221;</em> is to return a new  object. Therefore you can&#8217;t use a setter method on an immutable object,  as, even if it returns a new one, the runtime will ignore the return  value and set to the variable the argument that was received. On the  other hand, I don&#8217;t think this can be changed without breaking a lot of  existing code.</li>
</ul>
<p>Several  of this annoyances can be solved with a heavy dose of open classes,   s-expressions manipulation (using Parse Tree) and meta-programming in  general. <a href="http://www.paulgraham.com/knuth.html">Knuth has said</a> that: <em>Language designers also have an obligation  to provide  languages that encourage good style, since we all know that style is  strongly influenced by the language in which it is expressed</em>. Fully agreeing with such <a href="http://www.knowledgerush.com/kr/encyclopedia/Sapir-Whorf_Hypothesis/">Sapir-Whorf</a>-esque   sentence, I  feel it would be a good thing if the underlying listed solutions were  built into the language itself (and supported across implementations,  such as JRuby, Iron Ruby, Rubinius, Maglev), as it would not only  improve, even if a little bit, the language itself, but also they way its users write code.</p>
<p><strong>Update:</strong> Thanks Michael Fellinger for noting that ruby blocks are fully adherent to method definitions on 1.9, as they allow both default parameters and blocks as arguments.</p>
<br /> Tagged: <a href='http://metaphysicaldeveloper.wordpress.com/tag/functional/'>Functional</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/future/'>future</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/opinion/'>Opinion</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/ruby/'>Ruby</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/scala/'>scala</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/smalltalk/'>Smalltalk</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/metaphysicaldeveloper.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/metaphysicaldeveloper.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/metaphysicaldeveloper.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/metaphysicaldeveloper.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/metaphysicaldeveloper.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/metaphysicaldeveloper.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/metaphysicaldeveloper.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/metaphysicaldeveloper.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/metaphysicaldeveloper.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/metaphysicaldeveloper.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/metaphysicaldeveloper.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/metaphysicaldeveloper.wordpress.com/149/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=149&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2010/03/31/improving-ruby/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>
	</item>
		<item>
		<title>You can Trust your Data to the Cloud (In theory)</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2009/11/30/you-can-trust-your-data-to-the-cloud-in-theory/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2009/11/30/you-can-trust-your-data-to-the-cloud-in-theory/#comments</comments>
		<pubDate>Tue, 01 Dec 2009 01:54:24 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[Systems]]></category>
		<category><![CDATA[application]]></category>
		<category><![CDATA[cloud]]></category>
		<category><![CDATA[computing]]></category>
		<category><![CDATA[encryption]]></category>
		<category><![CDATA[homomorphic]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=140</guid>
		<description><![CDATA[Any sufficiently advanced technology is indistinguishable from magic - Arthur C. Clarke Cloud computing services such as Amazon EC2, Salesforce, Google App Engine and Heroku promise several advantages to the traditional datacenter model: economies of scale, reduced costs, simplification of IT infrastructure, scalability, reliability, the ability to pay-as-you-go. Nevertheless, there are some concerns regarding trust, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=140&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<blockquote><p><em>Any sufficiently advanced technology is indistinguishable from magic</em></p>
<p>- <a href="http://en.wikipedia.org/wiki/Arthur_C._Clarke">Arthur C. Clarke</a></p></blockquote>
<p><a href="http://www.infoq.com/news/2008/05/what-is-cloud-computing">Cloud computing</a> services such as <a href="http://aws.amazon.com/ec2/">Amazon EC2</a>, <a href="http://www.salesforce.com/platform/">Salesforce</a>, <a href="http://code.google.com/appengine/">Google App Engine</a> and <a href="http://heroku.com/">Heroku</a> promise several advantages to the traditional datacenter model: economies of scale, reduced costs, simplification of IT infrastructure, scalability, reliability, the ability to pay-as-you-go. Nevertheless, there are some <a href="http://www.infoq.com/presentations/Situation-normal-everything-must-change-Simon-Wardley">concerns</a> regarding trust, transparency, vendor lock-in and security.</p>
<p>One of the the most glaring controversies around cloud computing is the data privacy issue: your cloud provider has total access to all your data. While it can be argued that the trust issue is not that much more than deploying your own servers to a datacenter, it would be desirable if this was a non issue. Standard encryption schemes are generally useless to solve this issue: if data is encrypted/decrypted inside the cloud&#8217;s infrastructure, they will have access to the keys (at least as in memory data), not only the decrypted data visualized. Therefore, traditional schemes allow you only to safely retrieve and store encrypted data, which usually defies the purpose of using a cloud provider (mostly with huge amounts of data).</p>
<p>It was an open problem whether it would be even possible to compute on the unencrypted data without decrypting it, until <a href="http://crypto.stanford.edu/craig/">Craig Gentry</a>, currently working on <a href="http://domino.research.ibm.com/comm/research_projects.nsf/pages/security.index.html">IBM</a>&#8216;s Cryptography Research <a href="http://www.youtube.com/watch?v=qe-zmHoPW30&amp;feature=PlayList&amp;p=8447A2C2050A49DD&amp;playnext=1&amp;playnext_from=PL&amp;index=34">Group</a>,  recently proposed as part of his <a href="http://crypto.stanford.edu/craig/craig-thesis.pdf">Ph.D thesis</a>, a <a href="http://domino.research.ibm.com/comm/research_projects.nsf/pages/security.homoenc.html">scheme</a> (with the unique property of being <a href="http://en.wikipedia.org/wiki/Homomorphic_encryption#Fully_homomorphic_encryption">fully homomorphic</a>) that enables it. Whith this scheme, any function can be evaluated on the decrypted text without decrypting, while keeping the result encrypted in itself. The function can itself be made secret, therefore allowing the scheme to provide total privacy on input, output and computation.</p>
<p>The end result is: on any cloud setting where you can compute arbitrary functions, you can implement the proposed fully homomorphic scheme, and trust your data to your cloud provider without fear of giving up on privacy, without having to solely rely on Service Level Agreements.</p>
<p>The remaining issue is: the proposed scheme is efficient only under theoretical standards. Which means it runs on polynomial time on the security parameter. The problem is that the polynomial is of degree higher than six, which means it is not really practical to use it. For instance, Gentry <a href="http://themonetaryfuture.blogspot.com/2009/10/ibms-blindfolded-calculator.html">estimates</a> that if Google used it in its search, the results would take 1 trillion times more to be given. Therefore, the problem has been solved in theory, while still remaining unpractical. On the bright side, optimizing a possible problem tends to be easier than chasing an open one, or trying to prove it can&#8217;t be solved.</p>
<br /> Tagged: application, cloud, computing, encryption, homomorphic <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/metaphysicaldeveloper.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/metaphysicaldeveloper.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/metaphysicaldeveloper.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/metaphysicaldeveloper.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/metaphysicaldeveloper.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/metaphysicaldeveloper.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/metaphysicaldeveloper.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/metaphysicaldeveloper.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/metaphysicaldeveloper.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/metaphysicaldeveloper.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/metaphysicaldeveloper.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/metaphysicaldeveloper.wordpress.com/140/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&amp;blog=7215623&amp;post=140&amp;subd=metaphysicaldeveloper&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2009/11/30/you-can-trust-your-data-to-the-cloud-in-theory/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>
	</item>
	</channel>
</rss>
