<?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/"
	>

<channel>
	<title>Experimento imaginário &#187; Haskell</title>
	<atom:link href="http://joaopizani.hopto.org/en/category/haskell/feed/" rel="self" type="application/rss+xml" />
	<link>http://joaopizani.hopto.org/en/</link>
	<description>joaopizani&#039;s brain dump...</description>
	<lastBuildDate>Mon, 13 May 2013 00:15:04 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Haskell Ants EDSL: Implementation project in the &#8220;Advanced Functional Programming&#8221; course</title>
		<link>http://joaopizani.hopto.org/en/2013/03/haskell-ants-edsl/</link>
		<comments>http://joaopizani.hopto.org/en/2013/03/haskell-ants-edsl/#comments</comments>
		<pubDate>Sat, 02 Mar 2013 15:23:14 +0000</pubDate>
		<dc:creator>João Paulo</dc:creator>
				<category><![CDATA[Academia @en]]></category>
		<category><![CDATA[Haskell @en]]></category>
		<category><![CDATA[Masters @en]]></category>
		<category><![CDATA[Tech @en]]></category>
		<category><![CDATA[advanced functional programming]]></category>
		<category><![CDATA[ant simulation @en]]></category>
		<category><![CDATA[haskell @en]]></category>
		<category><![CDATA[haskell edsl @en]]></category>
		<category><![CDATA[utrecht university]]></category>

		<guid isPermaLink="false">http://joaopizani.hopto.org/?p=2170</guid>
		<description><![CDATA[In the second term of my master&#8217;s programme in Computing Science at Utrecht University, I followed (and liked very much) a course called &#8220;Advanced Functional Programming&#8221;. In this course, we study the theory that underpins the inner workings of functional &#8230; <a href="http://joaopizani.hopto.org/en/2013/03/haskell-ants-edsl/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>In the second term of my master&#8217;s programme in Computing Science at <a href="http://en.wikipedia.org/wiki/Utrecht_university">Utrecht University</a>, I followed (and liked very much) a course called &#8220;Advanced Functional Programming&#8221;. In this course, we study the theory that underpins the inner workings of functional programming languages (and in particular, Haskell). But, theory apart, we also developed a lot of practical assignments, <a href="https://github.com/joaopizani/haskell-ants-edsl-afp2012">the largest of which</a> I describe in this post.</p>
<p>I developed this project together with my colleagues <strong><a href="http://www.linkedin.com/pub/liewe-thomas-van-binsbergen/3a/587/659">Liewe Thomas van Binsbergen</a></strong> and the portuguese guy with the longest name I&#8217;ve ever seen: <strong>João Miguel Queiroz de Ataíde Agorreta de Alpuim</strong>. As a final project for the course, each &#8220;team&#8221; of students had to submit an entry to a competition that involved the simulation of ants searching for food in an environment. This &#8220;task&#8221; was also the one selected for the <a href="https://alliance.seas.upenn.edu/~plclub/cgi-bin/contest/index.php">programming contest of the International Conference on Functional Programming in 2004</a>&#8230;<br />
<span id="more-2170"></span></p>
<p>The <a href="http://joaopizani.hopto.org/wp-content/uploads/2013/03/icfp-contest-2004-rules.pdf">official task description</a> defines an assembly language for the ants, and that the ant colonies of the two teams will fight in &#8220;rounds&#8221; in a championship (with random maps chosen for each round); in each round the goal is to collect the most food possible at your anthill after a certain amount of time. The championship was run in a simulator, and the following animated gif shows how a small part of a simulation might look like:</p>
<p><a href="http://joaopizani.hopto.org/wp-content/uploads/2013/03/ants-edsl-animation.gif"><img class="aligncenter size-full wp-image-2162" alt="Ants Simulator" src="http://joaopizani.hopto.org/wp-content/uploads/2013/03/ants-edsl-animation.gif" width="400" height="360" /></a><br />
In this example, our team is the &#8220;red&#8221; team, and we are competing agains the all-time winner (in blue). Even though in this particular example we are losing by a long shot (there is little food in our hill), we weren&#8217;t so bad when competing with our classmates&#8230;</p>
<p>Anyways, <a href="https://github.com/joaopizani/haskell-ants-edsl-afp2012">the project (uploaded to GitHub)</a> is not about ant assembly, but about Advanced Functional Programming, so you might ask &#8220;What the hell does this all have to do with Haskell?&#8221;. The answer is simple: our real task was to implement an Embedded Domain-Specific Language (EDSL) in Haskell, allowing to express with a <strong>high level of abstraction</strong> the strategies we wanted our ants to follow. The &#8220;deliverables&#8221; of the project, thus, were twofold:</p>
<ul>
<li><strong>Ant EDSL library:</strong> A high-level API, made of fundamental strategies and of combinators allowing the user to build more complex strategies from simpler ones.</li>
<li><strong>The strategies themselves:</strong> Using the developed API, we needed to hand in two strategies (ant assembly files), that would take part in the championship against the rest of the class.</li>
</ul>
<p>Our EDSL was developed with a layered architecture, where the the evaluation of user-accessible functions in the API resulted in a value of type <strong>AntImperative</strong>, that was then converted (compiled) to proper ant assembly. This paradigm of EDSL is called &#8220;deep-embedded&#8221;. In the following figure, you can have an idea of how the project is structured:<br />
<a href="http://joaopizani.hopto.org/wp-content/uploads/2013/03/uu-ant-gen-layers.png"><img class="aligncenter size-full wp-image-2165" alt="uu-ant-gen-layers" src="http://joaopizani.hopto.org/wp-content/uploads/2013/03/uu-ant-gen-layers.png" width="300" height="432" /></a></p>
<p>Also, here it goes one of the basic strategies we submitted for the contest, so that you can have an idea of how it &#8220;feels&#8221; to write strategies in our EDSL:<br />
<script type="text/javascript" src="http://gist-it.appspot.com/github/joaopizani/haskell-ants-edsl-afp2012/blob/master/uu-ant-gen/Game/UUAntGen/Frontend/AntStrategies.hs?slice=158:185&amp;footer=no"></script></p>
<p>This particular strategy was based in the fact that ants born in the hill&#8217;s corners (each anthill had 6 corners) would draw &#8220;highways&#8221; with pheromones, that would mark a quick way for other ants to go back home whenever needed. Besides this, ants that found food would also leave a &#8220;trail&#8221; of pheromones leading to the highways, and these trails would consist a kind of &#8220;local roads&#8221;.</p>
<p>Finally, as a prize for your pacience in reading this post until here :), you can take a look at the slides that we prepared for the presentation of the project (click on the image to start the download):<br />
<a href="http://joaopizani.hopto.org/wp-content/uploads/2013/03/presentation-ants-edsl-afp2012.pdf"><img class="aligncenter size-full wp-image-2167" alt="slides-ants-edsl-afp2012" src="http://joaopizani.hopto.org/wp-content/uploads/2013/03/slides-ants-edsl-afp2012.png" width="664" height="496" /></a> <a href="http://joaopizani.hopto.org/wp-content/uploads/2013/03/presentation-ants-edsl-afp2012.pdf">presentation-ants-edsl-afp2012</a></p>
<p>That&#8217;s it! As soon as I have another cool project to show you guys, I will tell more about it here&#8230; See you soon! :)</p>
 <p><a href="http://joaopizani.hopto.org/?flattrss_redirect&amp;id=2170&amp;md5=580ec48b222c303ec9c80328d25b297b" title="Flattr" target="_blank"><img src="http://joaopizani.hopto.org/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://joaopizani.hopto.org/en/2013/03/haskell-ants-edsl/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=joaopizani&amp;popout=1&amp;url=http%3A%2F%2Fjoaopizani.hopto.org%2Fen%2F2013%2F03%2Fhaskell-ants-edsl%2F&amp;language=en_GB&amp;category=text&amp;title=Haskell+Ants+EDSL%3A+Implementation+project+in+the+%26%238220%3BAdvanced+Functional+Programming%26%238221%3B+course&amp;description=In+the+second+term+of+my+master%26%238217%3Bs+programme+in+Computing+Science+at+Utrecht+University%2C+I+followed+%28and+liked+very+much%29+a+course+called+%26%238220%3BAdvanced+Functional+Programming%26%238221%3B.+In+this+course%2C+we...&amp;tags=advanced+functional+programming%2Cant+simulation%2Chaskell%2Chaskell+edsl%2Cutrecht+university%2Cblog" type="text/html" />
	</item>
		<item>
		<title>Old but good lambdacat</title>
		<link>http://joaopizani.hopto.org/en/2012/11/old-but-good/</link>
		<comments>http://joaopizani.hopto.org/en/2012/11/old-but-good/#comments</comments>
		<pubDate>Fri, 22 Feb 2013 16:30:43 +0000</pubDate>
		<dc:creator>João Paulo</dc:creator>
				<category><![CDATA[Day-to-day]]></category>
		<category><![CDATA[Haskell @en]]></category>
		<category><![CDATA[haskell @en]]></category>
		<category><![CDATA[lambdacats]]></category>
		<category><![CDATA[loop]]></category>

		<guid isPermaLink="false">http://joaopizani.hopto.org/?p=1709</guid>
		<description><![CDATA[Só os bons entenderão: Just the smart people will get it: &#160;]]></description>
				<content:encoded><![CDATA[<p>Só os bons entenderão:</p>
<p>Just the smart people will get it:</p>
<div id="attachment_1410" class="wp-caption aligncenter" style="width: 330px"><a href="http://joaopizani.hopto.org/wp-content/uploads/2012/11/recursive_cats.gif"><img class="size-full wp-image-1410" title="Maru can haz boxed recursion" src="http://joaopizani.hopto.org/wp-content/uploads/2012/11/recursive_cats.gif" alt="Maru can haz boxed recursion" width="320" height="205" /></a><p class="wp-caption-text">Just because &#8220;ones = 1 : ones&#8221; was too much of a boring example&#8230;</p></div>
<p>&nbsp;</p>
 <p><a href="http://joaopizani.hopto.org/?flattrss_redirect&amp;id=1709&amp;md5=f725cd7e81d541763bf7f6ed5e1697a9" title="Flattr" target="_blank"><img src="http://joaopizani.hopto.org/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://joaopizani.hopto.org/en/2012/11/old-but-good/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=joaopizani&amp;popout=1&amp;url=http%3A%2F%2Fjoaopizani.hopto.org%2Fen%2F2012%2F11%2Fold-but-good%2F&amp;language=en_GB&amp;category=images&amp;title=Old+but+good+lambdacat&amp;description=S%C3%B3+os+bons+entender%C3%A3o%3A+Just+the+smart+people+will+get+it%3A+%26nbsp%3B&amp;tags=haskell%2Clambdacats%2Cloop%2Cblog" type="text/html" />
	</item>
		<item>
		<title>Haskell Kata: Conway&#8217;s Game of Life</title>
		<link>http://joaopizani.hopto.org/en/2012/01/haskell-kata-game-of-life/</link>
		<comments>http://joaopizani.hopto.org/en/2012/01/haskell-kata-game-of-life/#comments</comments>
		<pubDate>Tue, 26 Feb 2013 01:30:31 +0000</pubDate>
		<dc:creator>João Paulo</dc:creator>
				<category><![CDATA[Haskell @en]]></category>
		<category><![CDATA[Tech @en]]></category>

		<guid isPermaLink="false">http://joaopizani.hopto.org/?p=1949</guid>
		<description><![CDATA[Hi everybody! Today I am going to write about another Code Kata experience I had using Haskell. This time the code didn&#8217;t come directly from a Coding Dojo (live meeting with friends), but rather from an &#8220;enhancement&#8221; over the solution &#8230; <a href="http://joaopizani.hopto.org/en/2012/01/haskell-kata-game-of-life/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Hi everybody! Today I am going to write about another <a href="http://codekata.pragprog.com">Code Kata</a> experience I had using Haskell. This time the code didn&#8217;t come directly from a Coding Dojo (live meeting with friends), but rather from an &#8220;enhancement&#8221; over the solution we wrote at a meeting.</p>
<p>In that Coding Dojo we wanted to solve the <a href="http://codingdojo.org/cgi-bin/wiki.pl?KataGameOfLife">&#8220;Game Of Life&#8221;</a> problem. The goal was mainly to &#8211; given an initial configuration &#8211; evolve the world in one generation and print back this evolved state. For those of you who never heard about Conway&#8217;s Game of Life, its <a>article on Wikipedia</a> can be very clarifying.</p>
<p>So we did it, and we solved the problem, but &#8211; as always &#8211; I wanted very badly to try to solve the same problem using Haskell (instead of Python). At home, I coded it up in Haskell in around 30min, and the code was concise and elegant&#8230; In fact, this was so easy that I decided I needed some bigger challenge, something <strong>graphical</strong>, why not? Then I gave the awesome <a href="http://hackage.haskell.org/packages/archive/gloss/1.6.0.1/doc/html/Graphics-Gloss.html">Gloss</a> graphics library another chance, and I was AGAIN impressed with the results.<br />
<span id="more-1949"></span></p>
<p>So let&#8217;s start our Haskell Kata routine, by first describing the problem itself and then the beautiful Haskell solution&#8230;</p>
<h2>Problem Description</h2>
<p><em>(This problem description is blatantly copied from the correspondent Coding Dojo Wiki <a href="http://codingdojo.org/cgi-bin/wiki.pl?KataGameOfLife">entry</a>, as of 2012-01-19)</em></p>
<p>This Kata is about calculating the next generation of Conway&#8217;s Game of Life, given any starting position. Take a look at <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">Wikipedia</a> for background.</p>
<p>You start with a two-dimensional grid of cells, where each cell is either alive or dead. In this version of the problem, the grid is finite, and no life can exist off the edges. When calculating the next generation of the grid, follow these rules:</p>
<ul>
<li>Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.</li>
<li>Any live cell with more than three live neighbours dies, as if by overcrowding.</li>
<li>Any live cell with two or three live neighbours lives on to the next generation.</li>
<li>Any dead cell with exactly three live neighbours becomes a live cell.</li>
</ul>
<p>You should write a program that can accept an arbitrary grid of cells, and will output a similar grid showing the next generation.</p>
<h3>Input and Output</h3>
<p>The input starting position is given through a text file that looks like this:</p>
<pre>........
....*...
...**...
........</pre>
<p>And the output could look like:</p>
<pre>........
...**...
...**...
........</pre>
<p>This format was chosen because it is very easily parsed in most languages. OBS: It is VERY, VERY easily parsed in Haskell :)</p>
<p>&nbsp;</p>
<h2>Proposed &#8220;solution&#8221; in Haskell</h2>
<p><strong>SPOILER ALERT: DO NOT KEEP READING if you want to try solving this problem for yourself.</strong></p>
<p>As I said in the beginning of the post, my code isn&#8217;t really a solution to the given problem, but rather an improvement over it. It improves a simple solution in two ways:</p>
<ol>
<li>It handles more than one generation. It is actually a live simulation</li>
<li>It has a graphical interface to display the simulation</li>
</ol>
<p>Even though the code is bigger (because of these enhancements) it is still very concise and readable, totaling some 150 lines of code (with lots of whitespace). And to keep it simple, we are going to start our tour of the solution by the module that deals with the &#8220;original&#8221; problem: we are going to look first at the functions to read and evolve the board for one generation. First of all, the parser for a starting position (imports omitted for brevity):<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/GlossGameOfLife/Parser.hs?footer=0&#038;slice=7:"></script><br />
Our parser was written using the easy-to-use, efficient and popular <a href="http://hackage.haskell.org/package/parsec-3.1.2">Parsec</a> library for Haskell, that allows us to describe a format to be recognized (a <strong>grammar</strong>) in Haskell itself, in a very readable and concise way. Parsec is a <strong>parser combinator</strong> library, which means that we build our &#8220;big&#8221; parser by combining smaller parsers, which are built by combining even smaller ones, and so on&#8230; until we reach the primitive parsers that come with Parsec like, for example, &#8220;char&#8221;, used to define the parser for a dead cell in the first line of the code above.</p>
<p>Indeed, the parsers &#8220;dead&#8221; (for a dead cell) and &#8220;alive&#8221; (for a live cell) are the most fundamental, and what they do is pretty simple: they <strong>map</strong> a dot or an upper-case &#8216;O&#8217; to False or True, respectively. We can take a look at the type signatures of &#8220;char&#8221; and &#8220;fmap&#8221; if we want to know more precisely what they do:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="haskell"><pre class="de1"><span class="kw3">fmap</span> ∷ <span class="br0">&#40;</span>a → b<span class="br0">&#41;</span> → f a → f b
char ∷ <span class="kw4">Char</span> → Parser <span class="kw4">Char</span>
<span class="sy0">...</span>
<span class="kw3">map</span> ∷ <span class="br0">&#40;</span>a → b<span class="br0">&#41;</span> → <span class="br0">&#91;</span>a<span class="br0">&#93;</span> → <span class="br0">&#91;</span>b<span class="br0">&#93;</span></pre></div></div></div></div></div></div></div>


<p>First of all, let&#8217;s talk about &#8220;char&#8221;. The exact type of &#8220;char&#8221; (as in the <a href="http://hackage.haskell.org/packages/archive/parsec/3.1.2/doc/html/Text-Parsec-Char.html#v:char">Parsec documentation</a>) is more general and uses type classes. The type shown above, however, is a valid specialization of the general type, suiting our usage. You can see that &#8220;char&#8221; takes a character and gives us a <strong>Parser that recognizes</strong> that character. However, we want &#8220;dead&#8221; to be of type <em>Parser Bool</em>, that is, a parser that returns a boolean; so we need a function that converts <em>Parser Char</em> to <em>Parser Bool</em>&#8230; And that&#8217;s the point where <a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base-4.4.1.0/Control-Monad.html#v:fmap">&#8220;fmap&#8221;</a> comes to help us!</p>
<p>You can see that not only the name, but also the type of &#8220;fmap&#8221; is very similar to that of &#8220;map&#8221;. In fact, &#8220;fmap&#8221; is a generalization of &#8220;map&#8221;: while &#8220;map&#8221; works only over lists, &#8220;fmap&#8221; works over any container. Well, then &#8220;fmap&#8221; is applicable to our situation, that&#8217;s because anything of type <em>Parser a</em> is a monad, and any monad is a container (<em>the fancy word for container is <a href="http://learnyouahaskell.com/making-our-own-types-and-typeclasses#the-functor-typeclass">&#8220;Functor&#8221;</a></em>). The last interesting detail is the function that we map over (char &#8216;.&#8217;) and (char &#8216;O&#8217;): The usage of &#8220;const&#8221; means that <strong>we don&#8217;t care about what the Parser returns</strong>, as long as it succeeds, we return either a True or a False.</p>
<p>The remaining parser code is even simpler; the top-level function in the parser module (&#8220;parseBoardFromFile&#8221;) is the only one that still deserves some commentary:<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/GlossGameOfLife/Parser.hs?footer=0&#038;slice=15:"></script><br />
This function takes a file name as input (<em>FilePath</em> is just a synonym for <em>String</em>) and performs some IO actions (reading the file and parsing its contents). As a result of these actions, it returns a matrix of booleans (that is, our <em>Board</em> \o/). The function <a href="http://hackage.haskell.org/packages/archive/parsec/3.1.2/doc/html/Text-Parsec-ByteString.html#v:parseFromFile">&#8220;parseFromFile&#8221;</a> comes from Parsec, and it does exactly what its name says, with a return type of <em>Either ParseError [[Bool]]</em>. Because &#8220;result&#8221; has this type, we use the <a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base-4.4.1.0/Data-Either.html#v:either">&#8220;either&#8221;</a> function in the next line. The &#8220;either&#8221; function is used whenever you need to <strong>decide what to do based on a value of type <em>Either</em></strong>. In our case, if the result is a correctly parsed matrix, we return it as-is (that&#8217;s what &#8220;id&#8221; does for us). But if it&#8217;s an erroneous parse, then we convert the ParseError to a string and terminate the program showing the error message (that&#8217;s what &#8220;(error ∘ show)&#8221; does for us).</p>
<p>Enough for parsing now, and on to what really matters: evolving a board one generation. We take care of this task in the Evolution module. The most important functions of this module are &#8220;evolve&#8221; and &#8220;eval&#8221;. &#8220;eval&#8221; is given a position on the board and returns whether the cell in that position should be dead or alive, based on its surroundings. &#8220;evolve&#8221; is given a board and just applies &#8220;eval&#8221; all over it to create the next-generation board. With one important consideration: it only looks at the inner cells in the board, i.e, all border cells are considered <strong>always dead</strong>. Here&#8217;s the code for &#8220;eval&#8221; and &#8220;evolve&#8221;:<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/GlossGameOfLife/Evolution.hs?footer=0&#038;slice=8:24"></script><br />
The function &#8220;aliveNeighbours&#8221; takes a board and a pair of coordinates, returning <strong>how many</strong> of the 8 surrounding cells are alive. Its definition is pretty boring and straightforward, so I won&#8217;t explain it &#8211; you&#8217;ll have to believe that it works :)</p>
<p>So, the code that we saw so far almost solves the original Kata problem &#8211; we only needed to add some pretty-printing of the board&#8230; BUT! But we are going to do something much nicer, much cooler: we are going to display our simulation in a graphical interface, like this:</p>
<div class="wp-caption aligncenter" style="width: 436px"><img title="Gosper Glider Gun" src="http://i.imgur.com/jCLp2.gif" alt="" width="426" height="211" /><p class="wp-caption-text">The &quot;Gosper glider gun&quot; o/o/o/</p></div>
<p>Before getting too excited, I have to warn you: the module dealing with drawing the graphics is the largest one (It has around 50 lines of code). However, if you run the program for yourself and watch the AWESOME resulting simulation, you&#8217;ll realize that 50 lines is a <strong>very good mark :)</strong></p>
<p>Anyways, 50 lines is still too much to be embedded in a blog post, so I&#8217;ll only give you the highlights &#8211; namely, the functions &#8220;drawModel&#8221;, &#8220;layout&#8221; and &#8220;activate&#8221;. Here&#8217;s their code:<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/GlossGameOfLife/Drawing.hs?footer=0&#038;slice=27:32"></script><br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/GlossGameOfLife/Drawing.hs?footer=0&#038;slice=49:63"></script><br />
Let&#8217;s begin with the easiest one: &#8220;activate&#8221; takes a matrix of pictures (all of them are squares) and assigns a color to each one, with the color depending on whether that position of the matrix is active or not in the underlying Game of Life board. The way in which we implemented &#8220;activate&#8221; is VERY typical in functional programming, and benefits largely from lazy evaluation. First, we apply &#8220;paintersFromBoard&#8221;, which has type:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="haskell"><pre class="de1">paintersFromBoard ∷ <span class="br0">&#91;</span><span class="br0">&#91;</span><span class="kw4">Bool</span><span class="br0">&#93;</span><span class="br0">&#93;</span> → <span class="br0">&#91;</span><span class="br0">&#91;</span>Picture → Picture<span class="br0">&#93;</span><span class="br0">&#93;</span></pre></div></div></div></div></div></div></div>


<p>It takes the board and transforms it into a <strong>matrix of functions</strong>. More specifically, each function in this matrix is a painter, transforming a picture into a new one by changing its color. Now we have two things to combine:</p>
<ol>
<li>A matrix of default-colored squares (by default they are all black)</li>
<li>A matrix of &#8220;painter functions&#8221;, one for each square</li>
</ol>
<p>To combine these, we use &#8220;applyFunctionMatrix&#8221; (not shown above). Its definition is very straightforward, but also very typical of functional programming languages. We define &#8220;applyFunctionMatrix&#8221; by &#8220;lifting&#8221; the usage of &#8220;applyFunctionList&#8221; to the outer list of the matrix (the list of lines). &#8220;applyFunctionList&#8221; is beautifully defined as follows:</p>
<p>Continuing in the Drawing module, we reach &#8220;layout&#8221;. The purpose of this function is to &#8211; given a list of &#8220;unplaced&#8221; pictures (all overlapping each other) &#8211; spread them with some padding between each other so that they fill a horizontal or vertical line. We want the resulting &#8220;array&#8221; of pictures to be centered around the point where all overlapping pictures <strong>currently are</strong> &#8211; that&#8217;s why we calculate the &#8220;middle&#8221; index as being half of the list&#8217;s length. We then use &#8220;move&#8221; to displace each picture by &#8220;i&#8221; steps in direction &#8220;dir&#8221;. The &#8220;move&#8221; function knows the size of the cells, so we only need to pass it how many &#8220;steps&#8221; we want to displace a cell, and a pixel-exact translation will be done for us.<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/GlossGameOfLife/Drawing.hs?footer=0&#038;slice=42:43"></script><br />
At last, the most important function in the drawing module &#8211; the core of the simulation: &#8220;drawModel&#8221;. Its type, <em>Board → Picture</em>, already tells us how much important it is. At each simulation step, the model is transformed by a call to &#8220;evolve&#8221;; then, our function &#8220;drawModel&#8221; is called by the <a href="http://hackage.haskell.org/packages/archive/gloss/1.6.0.1/doc/html/Graphics-Gloss-Interface-Simulate.html">Gloss Simulation Engine</a> to render to model into a Picture. The definition is a simple pipeline with the following steps:</p>
<ol>
<li>Create a l × c matrix of same-sized squares &#8211; by default they are all black and placed at (0,0)</li>
<li>Paint the squares according to the model</li>
<li>Place them &#8211; equally spaced &#8211; in a nice grid</li>
</ol>
<p>Ladies and gentlemen, having understood how to do a simulation step (&#8220;evolve&#8221;) and how to display the model (&#8220;drawModel&#8221;), we are almost DONE. I am only going to show you how the <a href="http://hackage.haskell.org/packages/archive/gloss/1.6.0.1/doc/html/Graphics-Gloss-Interface-Simulate.html#v:simulate">&#8220;simulate&#8221;</a> function from Gloss connects these pieces together. Our main function is basically just a call to &#8220;simulate&#8221;, like this:<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/GlossGameOfLife/GlossGameOfLife.hs?footer=0&#038;slice=11:"></script><br />
The <a>&#8220;simulate&#8221;</a> function takes 6 parameters, and while it might seem too much, they all actually make sense:</p>
<ol>
<li><strong>display:</strong> defines how gloss is going to show the simulation &#8211; the size and position of the window, etc.</li>
<li><strong>bg:</strong> background color for the drawing area</li>
<li><strong>fps:</strong> how many simulation steps happen in one second of real time</li>
<li><strong>initial:</strong> the initial model (that we read from the file)</li>
<li><strong>drawModel:</strong> a function that transforms the model into a <em>Picture</em></li>
<li><strong>step function:</strong> a function to advance the model one iteration. We use the lambda to ignore some parameters that are irrelevant for us</li>
</ol>
<p>THAT&#8217;S IT! TADA! Now we are done. As always, you can download the <em>cabalized</em> package with the source code from my GitHub repository (<a href="https://github.com/joaopizani/katas/tree/blog-05-2012/GlossGameOfLife">https://github.com/joaopizani/katas/tree/blog-05-2012GlossGameOfLife</a>), build and run it as follows:</p>
<pre>$ cd GlossGameOfLife
$ cabal-dev install</pre>
<p>Have fun!</p>
 <p><a href="http://joaopizani.hopto.org/?flattrss_redirect&amp;id=1949&amp;md5=5dbd72fd822252f54bf0379180bb95ac" title="Flattr" target="_blank"><img src="http://joaopizani.hopto.org/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://joaopizani.hopto.org/en/2012/01/haskell-kata-game-of-life/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=joaopizani&amp;popout=1&amp;url=http%3A%2F%2Fjoaopizani.hopto.org%2Fen%2F2012%2F01%2Fhaskell-kata-game-of-life%2F&amp;language=en_GB&amp;category=text&amp;title=Haskell+Kata%3A+Conway%26%238217%3Bs+Game+of+Life&amp;description=Hi+everybody%21+Today+I+am+going+to+write+about+another+Code+Kata+experience+I+had+using+Haskell.+This+time+the+code+didn%26%238217%3Bt+come+directly+from+a+Coding+Dojo+%28live+meeting...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Haskell synthesizer: playing with functional sound generation</title>
		<link>http://joaopizani.hopto.org/en/2012/01/haskell-synth/</link>
		<comments>http://joaopizani.hopto.org/en/2012/01/haskell-synth/#comments</comments>
		<pubDate>Tue, 26 Feb 2013 01:29:27 +0000</pubDate>
		<dc:creator>João Paulo</dc:creator>
				<category><![CDATA[Haskell @en]]></category>
		<category><![CDATA[Tech @en]]></category>

		<guid isPermaLink="false">http://joaopizani.hopto.org/?p=1948</guid>
		<description><![CDATA[Some time ago, in a cloudy friday afternoon, I had nothing to do. Me and my friends started talking about the Unix philosophy, and in particular, how everything in Unix is a file, even devices are represented as files. So &#8230; <a href="http://joaopizani.hopto.org/en/2012/01/haskell-synth/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Some time ago, in a cloudy friday afternoon, I had nothing to do. Me and my <a href="http://pet.inf.ufsc.br/membros">friends</a> started talking about the Unix philosophy, and in particular, how everything in Unix is a file, even <a href="http://en.wikipedia.org/wiki/Device_file">devices</a> are represented as files. So I thought: the sound card is a file! What happens if I write to it? Then we started feeding lots of files (PDFs, /dev/urandom, some source code and some images) to the sound card and where amused :)</p>
<p>But then we decided to have more fun and feed some more &#8220;organized&#8221; bytes to the sound card &#8211; we would generate our audio samples programmatically. And what better tool to do some data generation than Haskel!? So I started writing my first audio synthesizer, and after some hours it was ready and working awesomely&#8230; I was really excited with the results, so I just NEEDED to share this nice piece of code with the world :)</p>
<p>My Haskell tone synthesizer takes a &#8220;score file&#8221; as input, that describes the tune you want the synthesizer to generate. This input file has a syntax very similar to the old Nokia Ringtone Composer syntax&#8230; The program reads the score from the file and outputs a lot of bytes to standard output. If you redirect the standard output to your sound card, you will hear your favorite tunes! So let me guide you through a tour of this program&#8217;s source code:<br />
<span id="more-1948"></span></p>
<p>This tour will be in top-bottom style: we will start by looking at the Main module and its major processing steps, and then dwell a bit deeper into some of the most important functions of each module. So, to start, here is the entire Main module:<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/ToneSynthesizer/ToneSynthesizer.hs?footer=0"></script></p>
<p>As you can see in the second line of &#8220;main&#8221;, we need 2 command-line parameters: &#8220;file&#8221; and &#8220;bpmStr&#8221; (which will be read into an Int called &#8220;bpm&#8221;). &#8220;file&#8221; is the name of the file containing our score, and &#8220;bpm_&#8221; is the tempo in which the song will be played (in beats per minute &#8211; BPM). We then proceed to parse the score from the file, using the &#8220;parseFromFile&#8221; function (from <a href="http://hackage.haskell.org/package/parsec-3.1.2">Parsec</a>). This function takes a parser to apply and a filename from which to read an input stream. Our conveniently-named &#8220;score&#8221; parser is defined in a separate file (<em>Melody.hs</em>) and will not be further discussed&#8230; You can see it if you download the full source code at the end of the post.</p>
<p>The &#8220;parseFromFile&#8221; function has type <em>Parser a → String → Either ParseError a</em>, which means its result is <em>Either</em> our desired outcome (<em>Right [Note]</em>) or an error (<em>Left ParseError</em>). We then apply the <a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base-4.4.1.0/Data-Either.html">&#8220;either&#8221;</a> function over &#8220;parsedScore&#8221; to do case analysis: in case a perfect parse ocurred, the &#8220;id&#8221; function is applied and the result is kept as-is; in case a parse error has been found, we apply (error ∘ show) &#8211; which just displays the error message on standard output and terminates the program. The next &#8220;big step&#8221; in the program is to turn the music into concrete form.</p>
<p>The parsed score is a sequence of musical notes with relative durations (1, 1/2, 1/4, etc.) and abstract pitch names (C, D, E, etc.), so the the task of &#8220;concrete bpm&#8221; is to take each abstract note and make both pitch and duration &#8220;concrete&#8221;. Its type is:<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/ToneSynthesizer/Parameters.hs?footer=0&#038;slice=20:21"></script><br />
It takes a Tempo and a Note and produces a pair representing a concrete sound, where the first element is the frequency of this sound (in Hz) and the second element is its duration (in seconds).</p>
<p>After we have our list of sound pairs to play (&#8220;concreteMusic&#8221;), we reach the last and most important step, which is to actually generate the samples and output them, using &#8220;concreteMusic&#8221; to <strong>guide the generation process</strong>. This is done by &#8220;produceStream&#8221;. For each pair of frequency and duration &#8220;(f,t)&#8221;, the following is done:</p>
<ol>
<li>Samples for a (infinite) square wave of frequency <em>f</em> are generated by a call to &#8220;signal f&#8221;.</li>
<li>This signal is then &#8220;sliced&#8221; to obtain a piece of length <em>t</em>, by a call to &#8220;slice t&#8221;</li>
</ol>
<p>Finally, this whole sequence of &#8220;signal slices&#8221; is concatenated together into a ByteString which goes to standard output&#8230; Now going deeper, we will dive to file &#8220;Signal.hs&#8221; and take a look at the definitions of &#8220;signal&#8221; and &#8220;slice&#8221;, along with some helper functions:<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/ToneSynthesizer/Signal.hs?footer=0&#038;slice=8:"></script></p>
<p>Let&#8217;s start explaining this module (&#8220;Signal.hs&#8221;) from the ground up: our signal is an infinite sound wave. The most characteristic feature of a wave is that it&#8217;s <strong>periodic</strong>, which means it&#8217;s just an infinite repetition of a <strong>pattern</strong>. Therefore we have the &#8220;period&#8221; function here, which, given the number of samples to generate and the desired waveform, generates a list of samples that follows this waveform. So that&#8217;s how &#8220;signal&#8221; uses &#8220;period&#8221; in order to make a wave: it takes the requested frequency and then calculates (according to the sample rate) <strong>how many samples</strong> are there in one period. It uses the &#8220;period&#8221; function to generate a &#8220;singlePeriod&#8221;, which it then cycles and packs into an infinite and repetitive ByteString. The &#8220;silence&#8221; function is only there to produce a &#8220;dummy&#8221; period when we need a pause. It doesn&#8217;t need to have more than one sample, however, because it&#8217;s going to be transformed into an infinite ByteString of 0&#8242;s anyway&#8230;</p>
<p>The &#8220;cycleAndPack&#8221; function takes one period (<em>[Int]</em>) and transforms it into a (lazy) infinite <a href="http://hackage.haskell.org/package/bytestring-0.9.2.0">ByteString</a>. Its type should be very self-evident, after all. The &#8220;(map fromIntegral)&#8221; part transforms our <em>[Int]</em> into <em>[Word8]</em>, which then serves as input for &#8220;B.pack&#8221;, which actually creates the ByteString, then made infinite (repeated indefinitely) by &#8220;B.cycle&#8221;.</p>
<p>Now to the <strong>slicing</strong>! :) The task of the &#8220;slice&#8221; function is to transform an infinite wave (infinite ByteString) of a certain frequency into a finite wave (finite ByteString), with the requested duration in seconds. The type of slice is:<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/ToneSynthesizer/Signal.hs?footer=0&#038;slice=8:9"></script><br />
Which makes evident its role as a &#8220;ByteString-transforming&#8221; function. The definition of &#8220;slice&#8221; &#8211; in point-free style &#8211; also helps explaining what it does: to slice an infinite ByteString is just to <strong>take n</strong> of its first elements, where <strong>n</strong> is the product of the desired time in seconds by the sampling rate in Hz.</p>
<p>Before continuing to show you the code, allow me to take a slight detour and say how Haskell&#8217;s purely-functional features help us express this program in such an elegant (and still efficient) way:</p>
<ol>
<li><strong>Lazyness</strong>: Due to the possibility of using lazy evaluation, we were able to represent sound waves as infinite streams of samples, separating stream generation from stream usage.</li>
<li><strong>Referential transparency</strong>: Haskell&#8217;s purity means that every function is transparent. Thus, the value of <strong>any expression</strong> needs only to be computed <strong>once</strong>, and can be substituted for all occurrences of that expression. This is important because &#8211; in a single song &#8211; several notes will have the same frequency (and therefore will result in identical signals). Thanks to referential transparency, it is <strong>guaranteed</strong> that we only need to compute &#8220;signal f&#8221; once for each f, and thus we will only have one stream for each frequency in our song.</li>
</ol>
<p>Well, having understood how &#8220;signal&#8221; and &#8220;slice&#8221; work, the puzzle is now almost entirely solved. The only remaining mystery should be how the actual input file (in Nokia-Composer-style) is parsed, but &#8211; as I said before &#8211; the parser is mostly straightforward and uses just basic Parsec. The input parser is the largest single piece of code in the whole synthesizer (only <strong>relatively</strong> big, but still small), so I&#8217;ll only show you a summarized version here and won&#8217;t even explain it. You can grab the full code at the end of the post and take a more careful look&#8230; So here it goes, the core of our input parser:<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/ToneSynthesizer/Melody.hs?footer=0&#038;slice=18:25"></script><br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/ToneSynthesizer/Melody.hs?footer=0&#038;slice=59:"></script></p>
<p>And now, a bit of fun: to finish up the post nicely, I have included some sample song files in the synthesizer&#8217;s tarball; then I ran the synthesizer over them and encoded the output as MP3. Now you can listen to two catchy tunes generated by Haskell!</p>
<ul>
<li><strong>Europe &#8211; The Final Countdown:</strong>
<ul>
<li>Song score:
<pre>p4, p8, b16, a16, b4, e4, p4, p8, c'16, b16, c'8, b8, a4, p4, p8, c'16, b16, c'4, e4, p4, p8, a16, g16, a8, g8, f#8, a8, g4, p8, f#16, g16, a4, p8, g16, a16, b8, a8, g8, f#8, e4, c'4, b2, p4, b16, c'16, b16, a16, b1</pre>
</li>
<li>MP3: <a href="http://joaopizani.hopto.org/wp-content/uploads/2012/01/finalcountdown.mp3">Download audio file (finalcountdown.mp3)</a></li>
</ul>
</li>
</ul>
<ul>
<li><strong>Zelda Main Theme:</strong>
<ul>
<li>Song score:
<pre>a#4, f4, f8, f16, a#16, a#16, c'16, d'16, d#'16, f'2, p8, f'8, f'8, f#'16, g#'16, a#'2, p8, a#'8, a#'8, a#'8, g#'16, f#'16, g#'8, g#'16,  f#'16, f'2</pre>
</li>
<li>MP3: <a href="http://joaopizani.hopto.org/wp-content/uploads/2012/01/zelda.mp3">Download audio file (zelda.mp3)</a></li>
</ul>
</li>
</ul>
<p>Finally, as always, there comes what REALLY matters: The Source Code. The code of this synthesizer, along with several of my other &#8220;toy programs&#8221;, lives in the &#8220;Katas&#8221; repository on GitHub. You can check it out here: <a href="https://github.com/joaopizani/katas">https://github.com/joaopizani/katas</a> .  Download the code as a .zip file or even clone the repository and then play freely!&#8230; I strongly recommend that you use <a href="http://hackage.haskell.org/package/cabal-dev">cabal-dev</a> to build all your Haskell projects, so in case you want to follow my recommendation, the steps to build and run (in Unix) the synthesizer are something like this:</p>
<pre>cd ToneSynthesizer
cabal-dev install
./cabal-dev/bin/tonesynthesizer songs/<chosen-song>  | aplay -t raw -f U8 -r 16000</pre>
<p>I wish you all a whole lot of excitement and fun while coding in Haskell, and would certainly appreciate suggestions and critique regarding the code I just shared with you. That&#8217;s all, folks! :)</p>
 <p><a href="http://joaopizani.hopto.org/?flattrss_redirect&amp;id=1948&amp;md5=4b91bf34be274d268f7d830235609365" title="Flattr" target="_blank"><img src="http://joaopizani.hopto.org/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://joaopizani.hopto.org/en/2012/01/haskell-synth/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
<enclosure url="http://joaopizani.hopto.org/wp-content/uploads/2012/01/finalcountdown.mp3" length="41364" type="audio/mpeg" />
<enclosure url="http://joaopizani.hopto.org/wp-content/uploads/2012/01/zelda.mp3" length="20196" type="audio/mpeg" />
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=joaopizani&amp;popout=1&amp;url=http%3A%2F%2Fjoaopizani.hopto.org%2Fen%2F2012%2F01%2Fhaskell-synth%2F&amp;language=en_GB&amp;category=text&amp;title=Haskell+synthesizer%3A+playing+with+functional+sound+generation&amp;description=Some+time+ago%2C+in+a+cloudy+friday+afternoon%2C+I+had+nothing+to+do.+Me+and+my+friends+started+talking+about+the+Unix+philosophy%2C+and+in+particular%2C+how+everything+in+Unix...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Haskell Kata: Bank OCR</title>
		<link>http://joaopizani.hopto.org/en/2012/01/haskell-kata-bankocr/</link>
		<comments>http://joaopizani.hopto.org/en/2012/01/haskell-kata-bankocr/#comments</comments>
		<pubDate>Tue, 26 Feb 2013 01:27:49 +0000</pubDate>
		<dc:creator>João Paulo</dc:creator>
				<category><![CDATA[Academia @en]]></category>
		<category><![CDATA[Bachelor]]></category>
		<category><![CDATA[Haskell @en]]></category>
		<category><![CDATA[Tech @en]]></category>

		<guid isPermaLink="false">http://joaopizani.hopto.org/?p=1946</guid>
		<description><![CDATA[Some time ago I used to attend (twice per month) &#8220;Coding Dojo UFSC&#8221;, the programming practice meeting organized by me and my friends at college&#8230; Sadly these meetings are not being organized anymore, but they were AWESOME. If you still &#8230; <a href="http://joaopizani.hopto.org/en/2012/01/haskell-kata-bankocr/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Some time ago I used to attend (twice per month) &#8220;Coding Dojo UFSC&#8221;, the programming practice meeting organized by me and my friends at college&#8230; Sadly these meetings are not being organized anymore, but they were AWESOME. If you still don&#8217;t know what a Coding Dojo is, all details are <a href="http://codingdojo.org/cgi-bin/wiki.pl?WhatIsCodingDojo">HERE</a>, but &#8211; put simply &#8211; a Coding Dojo is a regular meeting where a small group of computer programmers (typically 5 to 20 in a room) exercise their programming skill through <strong>mindful practice</strong> and a <strong>rigid methodology</strong>. In a Dojo, the most important is not solving the problem or being &#8220;the best&#8221;, not at all. The point is to feel at the end that you have &#8211; individually and as a group &#8211; improved your skill.</p>
<p>Our Dojos were pretty exciting, indeed, to the point that sometimes we would each rush home after the Dojo to try and solve the problem in our favorite language/framework. I solved some of these short programming challenges in Haskell, and I now want to post them here in the blog so that more people can enjoy the &#8211; supposed :) &#8211;  beauty of the code and give suggestions. In the first of this hopefully long series of posts, we are going to play with <a href="http://codingdojo.org/cgi-bin/wiki.pl?KataBankOCR">BankOCR</a>.<br />
<span id="more-1946"></span></p>
<h2>Problem description</h2>
<p>The acronym &#8220;OCR&#8221; in the problem description gives the hint: we want to recognize characters. But our task is much easier than building a full-fledged optical recognizer&#8230;</p>
<p>Our program&#8217;s input is going to be a text file containing digits from 0 to 9 in a &#8220;LED-display-like&#8221; format. Like this:</p>
<pre>    _  _     _  _  _  _  _
  | _| _||_||_ |_   ||_||_|
  ||_  _|  | _||_|  ||_| _|</pre>
<p>Our input text file has only one line of &#8220;7-segment&#8221; digits, where each digit has a height of 3 &#8220;segments&#8221; (lines) and a width also of 3 &#8220;segments&#8221; (columns). Our program must read the contents of this file and print the corresponding number on the standard output, which for the above example would be &#8220;123456789&#8243;.</p>
<p>In the <a href="http://codingdojo.org/cgi-bin/wiki.pl?KataBankOCR">official problem description</a>, there are several additional usage scenarios for this challenge: recognizing several lines of digits, validating the numbers and using error-correcting codes to return good numbers even with &#8220;dirty&#8221; input. We are going, however, to tackle only the basic challenge, which is to recognize a single line of well-formed digits.</p>
<h2>Haskell solution</h2>
<p><strong>SPOILER ALERT:  DO NOT KEEP READING if you want to try solving this problem for yourself.</strong></p>
<p>I believe that a Haskell solution for this problem turned out very idiomatic and relatively easy to understand. Besides, it is also very short: ignoring the lookup table, we have only some 10 lines of code! There it goes, the relevant part of the solution:<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/BankOCR/OCR.hs?footer=0&#038;slice=0:16"></script><br />
Our solution is a typical <a href="http://en.wikipedia.org/wiki/Filter_(Unix)">Unix filter</a>, and this very much justifies our usage of the function &#8220;interact&#8221; to define main&#8230; The &#8220;interact&#8221; function has the following type:</p>
<pre>interact ∷ (String → String) → IO ()</pre>
<p>&#8220;interact&#8221; takes a <strong>function from String to String</strong> as parameter and does Input/Output with the help of this function. One way to express what &#8220;interact&#8221; does is by saying that it connects standard input to standard output, but allowing the information to be <strong>transformed by the user function</strong> as it flows down the pipeline :)</p>
<p>Now for some commentary on the core of our recognizer, the &#8220;parse&#8221; function:</p>
<ol>
<li>The &#8220;transpose&#8221; function is in the standard library (the &#8220;Prelude&#8221;), and works over lists of lists (matrices). It turns lines into columns and vice-versa (pretty obvious :P)</li>
<li>&#8220;lines&#8221; is also in the Prelude, and has type <em>String → [String]</em>. It takes a big String and breaks it down to a list of smaller Strings, one per line</li>
<li>The &#8220;lookup&#8221; function returns a value from an associative table. In Haskell, an associative table is just a list of pairs: <em>[ (key, value) ]</em></li>
<li>&#8220;lookup&#8221; gives us a value of type <em>Maybe Char</em>. That because, generally speaking, the key might not be in the table (it <strong>maybe</strong> is there). So, to transform a <em>Maybe Char</em> in the <em>Char</em> that we want, we use &#8220;fromJust&#8221;. Of course that if we pass &#8220;Nothing&#8221; (a nonexistent value) to &#8220;fromJust&#8221;, the program will crash. We are only using &#8220;fromJust&#8221; here because WE ARE SURE that all digits are in the table&#8230;</li>
<li>The &#8220;chunk&#8221; function is in the &#8220;Data.List.Split&#8221; module, and does what its name (and parameter) suggests: returns same-sized groups of elements from its input list</li>
<li>About &#8220;dummy&#8221;: The problem description states that there&#8217;s a blank column between any two digits (as a separator). So, effectively,  we could treat each digit as having 4 columns &#8211; EXCEPT FOR THE FIRST ONE. So, to avoid handling corner cases, I forced the first digit to also have 4 columns by adding a &#8220;dummy&#8221; column to it. This &#8220;strategy&#8221; of transforming a corner case into a normal one and THEN treating all cases equally is VERY often found in functional programs</li>
</ol>
<p>Well, after understanding how it works, we can now run the program, like this:</p>
<pre>joaopizani@rabbithole:~$ cat twohundredfiftysix
 _   _   _ 
 _| |_  |_ 
|_   _| |_|

joaopizani@rabbithole:~$ cat twohundredfiftysix | ./OCR
256</pre>
<p>Of course you don&#8217;t have to believe me, and you can check that the program work by yourself. Copy the code from my &#8220;katas&#8221; repository on GitHub (<a href="https://github.com/joaopizani/katas/blob/blog-05-2012/BankOCR/OCR.hs">https://github.com/joaopizani/katas/blob/blog-05-2012/BankOCR/OCR.hs</a>), compile it and run it!  There&#8217;s a small dependency on the &#8220;Data.List.Split&#8221; module, so the commands for compiling your source file and running the program are as follows:</p>
<pre>cabal install split
ghc --make OCR.hs
cat &lt;input-file&gt; | ./OCR</pre>
<p>That&#8217;s all, folks!  Thanks for reading and have FUN coding in Haskell&#8230; In case you have any suggestion or you want to criticize the solution in any way, please do so in the comments :)</p>
 <p><a href="http://joaopizani.hopto.org/?flattrss_redirect&amp;id=1946&amp;md5=0be6f4aa5e1324b341b7b887e222f3b6" title="Flattr" target="_blank"><img src="http://joaopizani.hopto.org/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://joaopizani.hopto.org/en/2012/01/haskell-kata-bankocr/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=joaopizani&amp;popout=1&amp;url=http%3A%2F%2Fjoaopizani.hopto.org%2Fen%2F2012%2F01%2Fhaskell-kata-bankocr%2F&amp;language=en_GB&amp;category=text&amp;title=Haskell+Kata%3A+Bank+OCR&amp;description=Some+time+ago+I+used+to+attend+%28twice+per+month%29+%26%238220%3BCoding+Dojo+UFSC%26%238221%3B%2C+the+programming+practice+meeting+organized+by+me+and+my+friends+at+college%26%238230%3B+Sadly+these+meetings+are+not...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Haskell lottery: a nice and easy example of monads and monad transformers</title>
		<link>http://joaopizani.hopto.org/en/2012/01/haskell-transformers/</link>
		<comments>http://joaopizani.hopto.org/en/2012/01/haskell-transformers/#comments</comments>
		<pubDate>Tue, 26 Feb 2013 01:26:32 +0000</pubDate>
		<dc:creator>João Paulo</dc:creator>
				<category><![CDATA[Day-to-day]]></category>
		<category><![CDATA[Haskell @en]]></category>
		<category><![CDATA[Tech @en]]></category>

		<guid isPermaLink="false">http://joaopizani.hopto.org/?p=1945</guid>
		<description><![CDATA[My humble understanding of monads in Haskell began some years ago, when I heard that IO was a Monad (whatever that was)&#8230; Despite hearing the dreaded &#8220;M&#8221; word, I wasn&#8217;t much scared and carried on programming my little Haskell programs, &#8230; <a href="http://joaopizani.hopto.org/en/2012/01/haskell-transformers/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>My humble understanding of monads in Haskell began some years ago, when I heard that IO was a Monad (whatever that was)&#8230; Despite hearing the dreaded &#8220;M&#8221; word, I wasn&#8217;t much scared and carried on programming my little Haskell programs, using &#8220;putStrLn&#8221;, &#8220;getLine&#8221;, &#8220;readFile&#8221;, &#8220;writeFile&#8221; and etc. Then, in my 3rd year in college, I decided to implement a graphical application for manipulating finite automata, using GTK (<a href="http://projects.haskell.org/gtk2hs/" target="_blank">Gtk2Hs</a>). During the development of this program, a huge part of my functions started to get &#8220;infected&#8221; with &#8220;IO&#8221; in their types, so I thought it would be a nice idea to think a bit deeper about this &#8220;Monad&#8221; thing.</p>
<p>At that time I discovered that there are A LOT of monads in Haskell, and that A LOT of them are useful and popular &#8211; even though you might not know that they are monads&#8230; There is the State Monad, Parser monads, Reader and Writer monads, the Error monads, the Either Monad, the Maybe Monad and even the List Monad!!! YES! (Maybe a) and [a] are monads! :D Well, &#8220;all of these things are monads, that&#8217;s very nice, but why should I care?&#8221;, you might ask. I hope to give you just a bit of an answer with the example in this post.<br />
<span id="more-1945"></span><br />
In this post, I will assume that you have at least some experience with Haskell, and that you have messed around with at least IO (maybe with Maybe too, hun? :P)&#8230;</p>
<p>So, every year we have a tradition in Brazil, which is a big lottery run on December 31, with a huge prize. This year my family bought 180 tickets, and I wrote a program to check if any of them had the 6 winner numbers shown on TV. I wrote this program in Haskell &#8211; of course &#8211; and this time I was, again, forced to deepen my understanding of monads AND monad transformers to get it done.</p>
<p>The program should work as follows: A file containing all 180 tickets (each with 6 numbers) must be read. Then 6 rounds of user input must happen: in each round, the user types a number and the program matches the current collection of user-typed numbers with all tickets. Then, the 5 tickets with the most &#8220;lucky&#8221; numbers are printed on the screen. Again, six of these &#8220;rounds&#8221; must happen.</p>
<p>I started modelling my program from the bottom-up, by defining a datatype to represent a lottery ticket, a &#8220;Combination&#8221; of lottery numbers:<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/HaskellLottery/Main.hs?footer=0&#038;slice=9:20"></script></p>
<p>Notice that a Combination has two <a href="http://hackage.haskell.org/packages/archive/containers/0.4.2.0/doc/html/Data-IntSet.html" target="_blank">sets of ints</a>, a &#8220;lucky&#8221; and an &#8220;unlucky&#8221; one. The lucky one contains the numbers belonging to this combination that &#8220;showed up&#8221; on TV, while the unlucky ones are the rest&#8230; Also, the Ord instance for Combination is interesting: a combination is <strong>&#8220;larger&#8221;</strong> than another if the size of it&#8217;s lucky set is bigger. I use &#8220;(flip compare)&#8221; there just to make clearer that we are defining the notion of &#8220;larger&#8221; instead of &#8220;lesser or equal&#8221; (more common).</p>
<p>I then proceeded to implement the reading of the file into a list of Combination. This part is a bit out-of-context in this post, but I tried to make nice use of monadic features <em>even here</em>:<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/HaskellLottery/Main.hs?footer=0&#038;slice=22:34"></script></p>
<p>Comparing the types of &#8220;makeCombination&#8221; and &#8220;makeCombinations&#8221;, for example, you see that they have <strong>a lot in common</strong>. I think that most people would implement makeCombinations as &#8220;makeCombinations = map makeCombination&#8221;. I just used &#8220;<a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad.html#g:7" target="_blank">liftM</a>&#8221; to make very clear that List is a Monad. Thus, we are lifting the &#8220;makeCombination&#8221; function <strong>into the List Monad</strong>. Then, at the definition of &#8220;readCombinations&#8221;, we have to use &#8220;liftM&#8221; again, but this time we <strong>lift into the IO Monad</strong>. So we use &#8220;liftM makeCombinations&#8221;. The expression &#8220;liftM makeCombinations&#8221; has type <em>IO [[Int]] → IO [Combination]</em>, and &#8220;readMatrix&#8221; has type <em>FilePath → IO [[Int]]</em>, so the types match nicely and allow an elegant composition, like this :)</p>
<pre>(FilePath → IO [[Int]]) ∘ (IO [[Int]] → IO [Combination]) ⇒ (FilePath → IO [Combination])</pre>
<p>Going further down the code, we reach the &#8220;core&#8221; function of our lottery checker: a function called &#8220;matchWithCombination&#8221;, which takes a &#8220;probe&#8221; (a number that showed up on TV) and one combination, returning a new combination with its lucky and unlucky components updated in case of a &#8220;match&#8221; with the probe:<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/HaskellLottery/Main.hs?footer=0&#038;slice=36:40"></script></p>
<p>We use IntSet.intersection to &#8220;match&#8221; the probe with the unlucky numbers, and then we update the current lucky set, by uniting it with the possible new lucky guy. The definition of &#8220;matchWithCombination&#8221; also shows a nice syntactical feature of Haskell: allowing us to both define AND use functions in <strong>infix</strong> form, by just putting backticks around the function name. Well.. we now define matchWithCombinations, very obviously: it&#8217;s ALMOST just a map (a lift to the List Monad), but we need to keep the probe argument as it is (unlifted), so that&#8217;s why the partial application:<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/HaskellLottery/Main.hs?footer=0&#038;slice=41:43"></script></p>
<p>Our program is now quite full-featured. Using matchWithCombinations. we can already take a number and see where it appears on all tickets. Two of the requirements we defined earlier are lacking, though:</p>
<ol>
<li>We need input (the user needs to <strong>type in</strong> the numbers in the terminal) and output (print the top 5 tickets on the terminal)</li>
<li>We need to perform 6 (input → process → output) &#8220;rounds&#8221;</li>
</ol>
<p>Our &#8220;matchWithCombinations&#8221; function can only do ONE &#8220;update&#8221; step, so we need to keep &#8220;threading&#8221; the results of calls to it in a chain, like this (sort of):</p>
<pre>(matchWithCombinations &lt;user-input&gt; (matchWithCombinations &lt;user-input&gt; (matchWithCombinations &lt;user-input&gt; originalCombs)))</pre>
<p>Usually, to accomplish this sort of &#8220;threading of a state&#8221; between function calls, we use the (obviously named) <strong><a href="http://www.haskell.org/haskellwiki/State_Monad" target="_blank">State Monad</a></strong>. And, as you might have already guessed, to perform input and output, we use the almighty <strong>IO Monad</strong>. It&#8217;s nice to see how each &#8220;layer of functionality&#8221; in your program corresponds to a layer in the <strong>&#8220;Monad onion&#8221;</strong> that your program becomes. So here we need to <strong>combine</strong> State and IO, two monads&#8230; Keep this in mind.</p>
<p>In a slight detour of our monad-combining craze, let me introduce you to the simple and humble &#8220;askForNewNumber&#8221; monad (a function in the IO Monad). Its task is to read a line of input from the terminal and (do its best) to convert it to an Int:<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/HaskellLottery/Main.hs?footer=0&#038;slice=45:47"></script></p>
<p>Now we want to use &#8220;askForNewNumber&#8221; in a more sophisticated monad, called &#8220;includeNewNumber&#8221;. The &#8220;includeNewNumber&#8221; monad will keep a <strong>state</strong> consisting of our combination list, and will (each time it&#8217;s called) read a number from the terminal and update the state with the newly matched combinations. The type of &#8220;includeNewNumber&#8221; has to be a combination of IO (because it uses &#8220;askForNewNumber&#8221;) and State. But how can we combine two monads??</p>
<p>Well, the good news is that we can usually combine two monads into <strong>another monad</strong>, by using this nifty thing called <strong>&#8220;monad transformers&#8221;</strong> :P In our case, we want to &#8220;transform&#8221; mere IO into a &#8220;State IO&#8221;. Look at the beautiful definition of &#8220;includeNewNumber&#8221; by yourself:<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/HaskellLottery/Main.hs?footer=0&#038;slice=48:53"></script></p>
<p>Literally, the type of &#8220;includeNewNumber&#8221; is <em>StateT [Combination] IO ()</em>, which means that we applied the <strong>&#8220;State Transformer&#8221;</strong> to the IO Monad, the type of our state being <em>[Combination]</em> and the type returned by IO being () (the unit type). StateT &#8220;wraps&#8221; IO with a layer of State, so now our program &#8220;onion&#8221; has officially two layers of functionality! Nice, hun!? :D Before going on, just one little explanation: <strong>IO must always be the innermost layer</strong>, mainly because when running the program all other layers are &#8220;peeled off&#8221;, and <em>IO ()</em> is what we need to give to &#8220;main&#8221;. The task of &#8220;peeling off&#8221; IO itself lays with the Haskell runtime system, and is out of our control :)</p>
<p>In the body of &#8220;includeNewNumber&#8221;, we need again to lift &#8220;askForNewNumber&#8221;, so that it resides on the outer StateT layer. After getting the probe we modify the state held by the monad using &#8220;matchWithCombinations probe&#8221;. Now we are VERY close to getting this program DONE®. In fact, we are so close that we could now run &#8220;includeNewNumber&#8221; six times&#8230; the numbers would be read and the combination list would be updated correctly; the only problem is that nothing would show up on the screen :(</p>
<p>Of course we are going to implement the last requirement (print the top 5 combinations after each round), but this optionality shows that monads (and monad transformers) allow you to write software in a very <strong>composable</strong> way, in which independent features are implemented in independent code. A very high <a href="http://en.wikipedia.org/wiki/Separation_of_concerns" target="_blank">Separation of Concerns</a> indeed. Let&#8217;s go on then with the implementation of our &#8220;feature full&#8221; function: &#8220;includeAndPrintTop5&#8243;<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/HaskellLottery/Main.hs?footer=0&#038;slice=54:58"></script></p>
<p>We first include a new number and get the (already updated) combinations state into &#8220;combs&#8221;. Then we pass &#8220;combs&#8221; through a pipeline which will print the top 5 combs on the screen. At the end of the pipeline, we need &#8220;lift&#8221; again, to transform the <em>IO ()</em> returned by putStrLn into the desired <em>StateT [Combination] IO ()</em>.</p>
<p>Dear reader, <strong>behold!</strong> Now comes the end of this post: I will show you the implementation of &#8220;main&#8221; for the lottery program&#8230;. With 2 lines of code! :)<br />
<script src="http://gist-it.appspot.com/github/joaopizani/katas/blob/blog-05-2012/HaskellLottery/Main.hs?footer=0&#038;slice=60:63"></script></p>
<p>First things first: we read the file into the suggestively-named &#8220;initial&#8221; value. We also need to perform 6 rounds of &#8220;includeAndPrintTop5&#8243;. That&#8217;s what &#8220;replicateM_ 6&#8243; is doing for us. If you want, you can do this repetition manually, like this:</p>
<pre>execStateT (includeAndPrintTop5 » includeAndPrintTop5 » includeAndPrintTop5 »
            includeAndPrintTop5 » includeAndPrintTop5 » includeAndPrintTop5 » return ()) initial</pre>
<p>Finally, we use execStateT to &#8220;peel off&#8221; the State Transformer and leave the rest of the job to our friend, IO (). The arguments to execStateT are the state monad it needs to &#8220;exec&#8221; and an initial state. It then runs the monad and doesn&#8217;t care about what is returned (in case you want the returned value, &#8220;evalStateT&#8221; is for you).</p>
<p>DONE! TA-DA! :D Please, do not believe my black magic. Grab the code on my &#8220;katas&#8221; GitHub repository <a href="https://github.com/joaopizani/katas" target="_blank">https://github.com/joaopizani/katas</a> and run for yourself, then change it and play with it&#8230; Have fun :)<br />
PS:</p>
<ol>
<li>If you played with lists before (you should have), you will know the &#8220;replicate&#8221; function from Data.List&#8230; Indeed, &#8220;replicateM_&#8221; and &#8220;replicate&#8221; work VERY similarly. Take a look (≡ means &#8220;is equivalent to&#8221;):
<pre>replicate 6 1   ≡ 1 : 1 : 1 : 1 : 1 : 1 : []
replicateM_ 6 m ≡ m » m » m » m » m » m » (return ())</pre>
<p>Now you can already start to imagine how List is a monad, can&#8217;t you? ;)</li>
<li>If you want to really know how &#8220;1 : 1 : 1 : []&#8221; and &#8220;m » m » m » (return ())&#8221; are related, take a look at the source code. Seriously, it&#8217;s <a href="http://www.haskell.org/ghc/docs/latest/html/libraries/base/src/Control-Monad.html#sequence_" target="_blank">HERE</a>.</li>
</ol>
<p>&nbsp;</p>
 <p><a href="http://joaopizani.hopto.org/?flattrss_redirect&amp;id=1945&amp;md5=21142099ba0c7bacda7a23248d2e306f" title="Flattr" target="_blank"><img src="http://joaopizani.hopto.org/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://joaopizani.hopto.org/en/2012/01/haskell-transformers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=joaopizani&amp;popout=1&amp;url=http%3A%2F%2Fjoaopizani.hopto.org%2Fen%2F2012%2F01%2Fhaskell-transformers%2F&amp;language=en_GB&amp;category=text&amp;title=Haskell+lottery%3A+a+nice+and+easy+example+of+monads+and+monad+transformers&amp;description=My+humble+understanding+of+monads+in+Haskell+began+some+years+ago%2C+when+I+heard+that+IO+was+a+Monad+%28whatever+that+was%29%26%238230%3B+Despite+hearing+the+dreaded+%26%238220%3BM%26%238221%3B+word%2C+I+wasn%26%238217%3Bt...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Playing with drawings and animations in Haskell</title>
		<link>http://joaopizani.hopto.org/en/2012/01/gloss-haskell/</link>
		<comments>http://joaopizani.hopto.org/en/2012/01/gloss-haskell/#comments</comments>
		<pubDate>Tue, 26 Feb 2013 01:25:28 +0000</pubDate>
		<dc:creator>João Paulo</dc:creator>
				<category><![CDATA[Day-to-day]]></category>
		<category><![CDATA[Haskell @en]]></category>
		<category><![CDATA[Tech @en]]></category>

		<guid isPermaLink="false">http://joaopizani.hopto.org/?p=1944</guid>
		<description><![CDATA[It&#8217;s an old adage of the computing profession that &#8220;Computer programming is the most fun you can have with your clothes on&#8221;, and certainly the most fun you can have with programming is when your program draws something on the &#8230; <a href="http://joaopizani.hopto.org/en/2012/01/gloss-haskell/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>It&#8217;s an old adage of the computing profession that &#8220;Computer programming is the most fun you can have with your clothes on&#8221;, and certainly the most fun you can have with programming is when your program <strong>draws</strong> something on the screen, or when your program shows an <strong>animation</strong>. It&#8217;s one of those activities that can make you spend hours late at night&#8230;</p>
<p>On December 31, 2011, I spent my morning and afternoon writing a program that would help me check if I had won the national New Year&#8217;s lottery. Of course, being such an important program, it HAD to have a nice, beautiful graphical interface. And of course the language I was going to use was Haskell; after all, I wanted to have some <strong>FUN</strong> writing it :)<br />
<span id="more-1944"></span><br />
I remembered that some months ago I came across the fantastic <a href="http://gloss.ouroborus.net/" target="_blank">gloss</a> library for Haskell, but didn&#8217;t have much time to play with it&#8230; so I decided to give &#8220;gloss&#8221; a try this time. Gloss is a Haskell library that allows the user to create and run 2D static images, animations and GAMES! It runs on top of OpenGL, so &#8211; if you have a reasonable graphics card &#8211; your game can even be fast :)</p>
<p>What I needed to draw in my lottery program was actually too simple and boring (just some colorful numbers), so in this post we&#8217;ll create a nicer animation with gloss: we will design a clock! Yes, a classic analog clock with three dials, sort of&#8230;</p>
<p>First of all, a huge part of the stuff that gloss manipulates has the type &#8220;<a href="http://hackage.haskell.org/packages/archive/gloss/1.6.0.1/doc/html/Graphics-Gloss-Data-Picture.html" target="_blank">Picture</a>&#8220;. And there are several convenient functions for creating fundamental pictures and transforming one picture into another. In fact, there is a &#8220;rectangleSolid&#8221; function, which is exactly what we need to create the dials of our clock. Here&#8217;s a black 50px by 200px rectangle:</p>
<pre>rectangleSolid 50 200</pre>
<p>We need three of these rectangles for our &#8220;clock&#8221;, one for each dial (seconds, minutes, hours). And each of them has a differente length. So this is how we defined our dials:</p>
<pre>baseLength w = 0.75 * w
secondsDialLength x = baseLength x
minutesDialLength x = secondsDialLength x * 0.75
hoursDialLength x = minutesDialLength x * 0.70</pre>
<pre>baseDial = rectangleSolid 15
secondsDial x = baseDial (secondsDialLength x)
minutesDial x = baseDial (minutesDialLength x)
hoursDial = baseDial . hoursDialLength</pre>
<p>I made the length of our dials variable, and it all depends on the parameter of &#8220;baseLength&#8221;, which is &#8220;w&#8221;. This is going to be the width of our clockface. You can see that we have three FUNCTIONS defining the dials, so the dial lengths are variable, but the <strong>proportion</strong> between the dials is fixed by us&#8230; Besides, all dials have the same width, so that&#8217;s why we defined &#8220;baseDial = rectangleSolid 15&#8243;. We are able to &#8220;fixate&#8221; or &#8220;bind&#8221; one parameter of rectangleSolid to 15, thus &#8220;baseDial&#8221; needs only one more parameter, which is the dial&#8217;s length. This ability to &#8220;bind&#8221; functions partially is a very nice feature of Haskell called &#8220;currying&#8221;. Chech it out here if you want to know more: <strong><a href="http://www.haskell.org/haskellwiki/Currying" target="_blank">Currying</a></strong></p>
<pre>hoursDial = baseDial . hoursDialLength</pre>
<p>The definition of &#8220;hoursDial&#8221; in the last line of the block seems to be very different from the others, doesn&#8217;t it? hoursDial is still a function, but where is it&#8217;s length (&#8220;x&#8221;) parameter?? Well, we don&#8217;t need it, because hoursDial is defined as a <strong>composition</strong> of the functions hoursDialLength and baseDial. Remember high school?</p>
<p><strong>(f ∘ g)(x) = f(g(x))</strong></p>
<p>So now compare the two definition of hoursDial below, substituting &#8220;baseDial&#8221; for &#8220;f&#8221; and &#8220;hoursDialLength&#8221; for &#8220;g&#8221;. Nice, hun?</p>
<pre>hoursDial x = baseDial (hoursDialLength x)
hoursDial = baseDial ∘ hoursDialLength</pre>
<p>Very often in Haskell we can use function composition to make code look less verbose (with less &#8220;dirt&#8221;) and easier to read.</p>
<p>Now, going on with our clock! Until now, we have got 3 nice <strong>static</strong> dials. We now need to make them move :) In gloss, we can make our pictures move by adding an extra parameter to the picture definition: the <strong>time</strong>. Take a look at this:</p>
<pre>movingSquare t = rotate (90 * t) (rectangleSolid 100 100)</pre>
<p>Our &#8220;movingSquare&#8221; is now an animation. Animations have type (Float → Picture), i.e, they are functions that give us <em>a picture (a frame) for each instant of time</em>! Cool idea, don&#8217;t you think? The time parameter (&#8220;t&#8221;) is the number of <em>seconds elapsed since the beginning of the animation</em>. Thus, in the example above, we are rotating our little square 90 degrees per second&#8230;</p>
<p>But the seconds dial of our clock needs to turn 6 degrees per second (in order to turn 360 degrees in one minute). And the minutes dial needs to be 60 times slower than the seconds dial, and so on&#8230; Thus, that&#8217;s how we define the speeds of our dials:</p>
<pre>secondsRotationSpeed t = 6 * t
minutesRotationSpeed t = secondsRotationSpeed t / 60
hoursRotationSpeed t = minutesRotationSpeed t / 60</pre>
<p>Our speed functions define how much a dial is turned (degrees), according to the time (seconds) elapsed. And now, with the speeds defined, we can very easily define our &#8220;moving objects&#8221; &#8211; our animated clock<br />
dials:</p>
<pre>seconds x t = rotate (secondsRotationSpeed t) (secondsDial x)
minutes x t = rotate (minutesRotationSpeed t) (minutesDial x)
hours x t = rotate (hoursRotationSpeed t) (hoursDial x)</pre>
<p>They still take that length parameter (&#8220;x&#8221;), but now they also take the time parameter (&#8220;t&#8221;). And the &#8220;core of the movement&#8221; here is the function &#8220;rotate&#8221;. The amount to rotate depends on the time, and the picture to be rotated is parameterized by the length we give (&#8220;x&#8221;).</p>
<p>Well, well, well&#8230; We can have now our clock. It will be very minimalistic (Apple style :P), so it will ONLY contain three dials and nothing more. If you have some Pictures, and want to build one single Picture<br />
out of them all, the appropriately named &#8220;pictures&#8221; function from gloss can help you:</p>
<pre>clock x t = pictures [dial x t | dial &lt;- [seconds, minutes, hours]]</pre>
<p>Our clock is an animation, so it has that trailing time (&#8220;t&#8221;) parameter, plus it has a variable size, which we pass throught the x parameter. We take each of our animated dials, and apply the SAME parameters to all of them. What it means, of course, is that &#8220;global time&#8221; &#8220;runs&#8221; at the same speed for all dials. This is not the case when the clock travels close to the speed of light, but nevertheless&#8230; :P</p>
<p>As a final touch of elegance, however, I wanted to add the possibility of accelerating time :) With the function &#8220;variableSpeedClock&#8221; below, we can make a second in our animation take less (or more) than a second in the real world. Take a look:</p>
<pre>variableSpeedClock speed x t = clock x (t * speed)</pre>
<p>We multiply t by the speed parameter, so (quite obviously) the larger the value of speed, the quicker one &#8220;second&#8221; will be.</p>
<p>That&#8217;s it, that&#8217;s our FULL funky minimalistic analog clock. We can now RUN the animation by calling the (also appropriately called) &#8220;<a href="http://hackage.haskell.org/packages/archive/gloss/1.6.0.1/doc/html/Graphics-Gloss-Interface-Animate.html" target="_blank">animate</a>&#8221; function from gloss:</p>
<pre>animate (InWindow "GlossClock" (size, size) (200,200)) white (variableSpeedClock speed' size')</pre>
<p>In case you want to run the code and see the beauty for yourself, there are two possibilities:</p>
<ol>
<li>Install the <a href="http://hackage.haskell.org/platform/" target="_blank">Haskell Platform</a> in your computer (for Ubuntu: &#8220;sudo apt-get install haskell-platform&#8221;), and afterwards install gloss (typing &#8220;cabal install gloss&#8221;). You can them grab the full code <a href="http://hpaste.org/56079" target="_blank">here</a>, compile<br />
it with &#8220;ghc &#8211;make Clock.hs&#8221; and RUN!</li>
<li>Using this <a href="http://dac4.designacourse.com:8000/" target="_blank">BEAUTIFUL GLOSS WEB INTERFACE</a>: Copy the code from <a href="http://hpaste.org/56080" target="_blank">HERE</a>, paste it into the text field on the page and click &#8220;run&#8221;!</li>
</ol>
<p>And never forget, fiddle with the code, change it and have fun! The code is licensed under Creative Commons sharealike bla bla bla&#8230; :D</p>
<p>&nbsp;</p>
<p>Thanks to <a href="http://www.cse.unsw.edu.au/~benl/" target="_blank">Ben Lippmeier</a> for creating gloss, and thanks a lot to Chris Smith for creating the gloss web interface. Chris has also taught an awesome &#8220;<a href="http://cdsmith.wordpress.com/2011/08/16/haskell-for-kids-week-1/" target="_blank">Haskell for kids</a>&#8221; course, which was very inspiring to me&#8230; That&#8217;s how I WANT to teach my kids about computers :)</p>
 <p><a href="http://joaopizani.hopto.org/?flattrss_redirect&amp;id=1944&amp;md5=f46c8e5b0c90760e10b0b79efe93c75c" title="Flattr" target="_blank"><img src="http://joaopizani.hopto.org/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://joaopizani.hopto.org/en/2012/01/gloss-haskell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=joaopizani&amp;popout=1&amp;url=http%3A%2F%2Fjoaopizani.hopto.org%2Fen%2F2012%2F01%2Fgloss-haskell%2F&amp;language=en_GB&amp;category=text&amp;title=Playing+with+drawings+and+animations+in+Haskell&amp;description=It%26%238217%3Bs+an+old+adage+of+the+computing+profession+that+%26%238220%3BComputer+programming+is+the+most+fun+you+can+have+with+your+clothes+on%26%238221%3B%2C+and+certainly+the+most+fun+you+can+have...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Haskell image processing &#8211; easy and automatically parallel</title>
		<link>http://joaopizani.hopto.org/en/2011/06/haskell-parallel-image-processing/</link>
		<comments>http://joaopizani.hopto.org/en/2011/06/haskell-parallel-image-processing/#comments</comments>
		<pubDate>Sat, 23 Feb 2013 10:45:57 +0000</pubDate>
		<dc:creator>João Paulo</dc:creator>
				<category><![CDATA[Academia @en]]></category>
		<category><![CDATA[Bachelor]]></category>
		<category><![CDATA[Haskell @en]]></category>
		<category><![CDATA[Tech @en]]></category>

		<guid isPermaLink="false">http://joaopizani.hopto.org/?p=1914</guid>
		<description><![CDATA[One of the subjects we learn about in the Pattern Recognition elective course here at UFSC is pattern recognition devired from image processing. Our group project is to implement a selective intrusion detector that uses only a webcam&#8230; This is &#8230; <a href="http://joaopizani.hopto.org/en/2011/06/haskell-parallel-image-processing/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>One of the subjects we learn about in the Pattern Recognition elective course here at <a href="http://ufsc.br">UFSC</a> is pattern recognition devired from image processing. Our group project is to implement a selective intrusion detector that uses only a webcam&#8230; This is pretty complicated, and involves several processing steps, much more dificult tham it might seem at a first glance :)</p>
<p>One of the most common processing steps performed to identify objects in an image is <a href="http://en.wikipedia.org/wiki/Edge_detection">edge detection</a>. Our first course assignment is to implement the <a href="http://en.wikipedia.org/wiki/Roberts_Cross">Roberts Cross</a> edge detection algorithm. Because of my wish to get up-to-speed and review my <a href="http://www.haskell.org/haskellwiki/Haskell">Haskell</a> knowledge, and also because this sort of algorithm is <strong>perfect</strong> for the functional paradigm, I decided to give Haskell a try! I&#8217;ll then show you the code, the pretty images and report my (almost painless) experience implementing it :P</p>
<p style="text-align: center;"><a rel="attachment wp-att-751" href="http://joaopizani.hopto.org/2011/06/haskell-parallel-image-processing/haskell-nl/"><img class="aligncenter size-full wp-image-751" title="haskell-nederlands" src="http://joaopizani.hopto.org/wp-content/uploads/2011/06/haskell-nl.png" alt="Dutch Haskell" width="128" height="128" /></a></p>
<p><span id="more-1914"></span><br />
One of the strongest selling points of functional programming is that code that is written according to the paradigm can be automatically parallelized. Roberts edge detection consists, for example, of nothing more than scanning an image, pixel by pixel, and applying a small matrix of coefficients that calculates the weighted average with its neighbours (it&#8217;s called Convolution by the guys at Wikipedia). Well, this &#8220;pixel by pixel&#8221; sort of algorithm is INHERENTLY parallel, and we can divide the task among as many thread as we want, without changing the semantics of the code. This is <strong>exactly</strong> what the <a href="http://hackage.haskell.org/package/repa">Repa</a> library does: it allows you to easily express several algorithms over multidimensional arrays and have them parallelized automatically.</p>
<p>Without any more explanation, here comes an example of executing the &#8220;Roberts&#8221; program with 1 thread, for an image of 1024&#215;768 pixels:</p>
<p>Original image:</p>
<p style="text-align: center;"><a rel="attachment wp-att-749" href="http://joaopizani.hopto.org/2011/06/haskell-parallel-image-processing/wow/"><img class="aligncenter size-full wp-image-749" title="WoW" src="http://joaopizani.hopto.org/wp-content/uploads/2011/06/wow.png" alt="WoW original" width="502" height="377" /></a></p>
<p style="text-align: left;">Edges:</p>
<p style="text-align: center;"><a rel="attachment wp-att-750" href="http://joaopizani.hopto.org/2011/06/haskell-parallel-image-processing/wow_/"><img class="size-full wp-image-750 aligncenter" title="WoWBordas" src="http://joaopizani.hopto.org/wp-content/uploads/2011/06/wow_.png" alt="WoW edges" width="502" height="377" /></a></p>
<p style="text-align: left;">Execution time (some of it is IO-bound):</p>
<pre style="text-align: left;">real	0m7.112s
user	0m7.044s
sys	0m0.020s</pre>
<p style="text-align: left;">Now to execute it with 2 and 4 threads, the only difference is that you need to run the program with some extra arguments on the command line:</p>
<pre style="text-align: left;">./Roberts wow.png wow_bordas.bmp +RTS -N{2,4}</pre>
<pre style="text-align: left;">(2 threads)
real	0m4.000s
user	0m7.176s
sys	0m0.076s</pre>
<pre style="text-align: left;">(4 threads)
real	0m3.096s
user	0m8.509s
sys	0m0.456s</pre>
<p style="text-align: left;">Disconsidering some synchronization overhead, the speedup in execution time is almost linear \o/\o/. I admit that processing time is still a bit high, but taking into account that I&#8217;m a complete n00b with this library the results are pretty promising!</p>
<p style="text-align: left;">I&#8217;m gonna even show you the code, because it&#8217;s really beautiful and reasonably small:</p>
<p><script src="https://gist.github.com/2718546.js"> </script></p>
<p style="text-align: left;">A TOTAL of 45 lines of code, including reading and writing from/to files. Amazing, isn&#8217;t it? :)</p>
 <p><a href="http://joaopizani.hopto.org/?flattrss_redirect&amp;id=1914&amp;md5=cd019a7ea3ae21f75b0814cbe128e43a" title="Flattr" target="_blank"><img src="http://joaopizani.hopto.org/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://joaopizani.hopto.org/en/2011/06/haskell-parallel-image-processing/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=joaopizani&amp;popout=1&amp;url=http%3A%2F%2Fjoaopizani.hopto.org%2Fen%2F2011%2F06%2Fhaskell-parallel-image-processing%2F&amp;language=en_GB&amp;category=text&amp;title=Haskell+image+processing+%26%238211%3B+easy+and+automatically+parallel&amp;description=One+of+the+subjects+we+learn+about+in+the+Pattern+Recognition+elective+course+here+at+UFSC+is+pattern+recognition+devired+from+image+processing.+Our+group+project+is+to+implement+a...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Learning and installing Haskell is easier than ever!</title>
		<link>http://joaopizani.hopto.org/en/2010/08/haskell-easy/</link>
		<comments>http://joaopizani.hopto.org/en/2010/08/haskell-easy/#comments</comments>
		<pubDate>Sat, 23 Feb 2013 10:15:48 +0000</pubDate>
		<dc:creator>João Paulo</dc:creator>
				<category><![CDATA[Haskell @en]]></category>
		<category><![CDATA[Tech @en]]></category>

		<guid isPermaLink="false">http://joaopizani.hopto.org/?p=1895</guid>
		<description><![CDATA[It&#8217;s been a long time since my last post about functional programming and the Haskell programming language&#8230; I&#8217;ve written a post last year showing all the reasons I think are enough to convince you [intlink id="155" type="post"]that you should learn &#8230; <a href="http://joaopizani.hopto.org/en/2010/08/haskell-easy/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>It&#8217;s been a long time since my last post about functional programming and the <a href="http://haskell.org"><strong>Haskell</strong></a> programming language&#8230; I&#8217;ve written a post last year showing all the reasons I think are enough to convince you <strong>[intlink id="155" type="post"]that you should learn Haskell[/intlink]</strong>. From then on much changed and I have great news to tell. The language is evolving in all aspects, and I&#8217;m lucky to witness this evolution \o/\o/</p>
<p>The Haskell compiler (<a href="http://www.haskell.org/ghc/">GHC</a> &#8211; The Glorious Haskell Compilation system) generates faster code release after release, the community of people using the language is booming, including big enterprises like Facebook :D There are Haskell libraries to accomplish every imaginable and unimaginable task, and these libraries are centralized and organized in the <strong><a href="http://hackage.haskell.org">Hackage</a></strong> repository. Are you using a library and need to search its documentation? Use <strong><a href="http://www.haskell.org/hoogle/">Hoogle</a></strong>, the central Haskell documentation search engine&#8230; BUT, in this huge pool of good news I want to pick two special ones:<br />
<span id="more-1895"></span><br />
1) Learning Haskell is easier than ever. In my old post I mentioned already the nice tutorial (for beginners) &#8220;<a href="http://learnyouahaskell.com/">Learn You a Haskell for Great Good!</a>&#8221; and the book &#8220;<a href="http://book.realworldhaskell.org/">Real World Haskell</a>&#8220;. Now, great guys have created an even more awesome tool to learn Haskell: if you want to follow a good Haskell tutorial, practicing as you read, and even though install NOTHING onto your PC, go to the &#8220;<a href="http://tryhaskell.org/">Try Haskell!</a>&#8221; website. It&#8217;s an interactive Haskell tutorial, you code as you learn, in the comfort of your favorite browser :)</p>
<p><a href="http://tryhaskell.org/"><img class="aligncenter size-full wp-image-432" title="Try Haskell!" src="http://joaopizani.hopto.org/wp-content/uploads/2010/08/try_haskell.png" alt="" width="328" height="55" /></a></p>
<p>2) If you enjoyed the test-drive and wanna install Haskell in your PC it&#8217;s also easier than ever. Now all the essential tools and libraries for a Haskell programmer are bundled in the <strong><a href="http://hackage.haskell.org/platform/">Haskell Platform</a></strong>. Everything tested, stable and working nicely together. You just need to go to the <a href="http://hackage.haskell.org/platform/">platform&#8217;s website</a>, choose your operating system, and install. Surely in Ubuntu the install process is the simplest of all: you add the repository and then type into a terminal:  &#8220;sudo aptitude install haskell-platform&#8221; :D</p>
<p><a href="http://hackage.haskell.org/platform/"><img class="aligncenter size-full wp-image-433" title="Haskell Platform" src="http://joaopizani.hopto.org/wp-content/uploads/2010/08/haskell_platform.png" alt="" width="300" height="103" /></a></p>
<p>And to prove that installation is really EASY, I&#8217;ve recorded a videocast of me installing the Haskell Platform on Ubuntu and put it on YouTube. Here it goes:<br />
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="480" height="385" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/RiTZWhmB86U&amp;hl=pt_BR&amp;fs=1?rel=0" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="480" height="385" src="http://www.youtube.com/v/RiTZWhmB86U&amp;hl=pt_BR&amp;fs=1?rel=0" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
 <p><a href="http://joaopizani.hopto.org/?flattrss_redirect&amp;id=1895&amp;md5=b109272ca69a904279ea17d396e36a37" title="Flattr" target="_blank"><img src="http://joaopizani.hopto.org/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://joaopizani.hopto.org/en/2010/08/haskell-easy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=joaopizani&amp;popout=1&amp;url=http%3A%2F%2Fjoaopizani.hopto.org%2Fen%2F2010%2F08%2Fhaskell-easy%2F&amp;language=en_GB&amp;category=text&amp;title=Learning+and+installing+Haskell+is+easier+than+ever%21&amp;description=It%26%238217%3Bs+been+a+long+time+since+my+last+post+about+functional+programming+and+the+Haskell+programming+language%26%238230%3B+I%26%238217%3Bve+written+a+post+last+year+showing+all+the+reasons+I+think+are...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Seminar presentation on Functional Programming and Haskell</title>
		<link>http://joaopizani.hopto.org/en/2009/06/haskell-fp-talk/</link>
		<comments>http://joaopizani.hopto.org/en/2009/06/haskell-fp-talk/#comments</comments>
		<pubDate>Sat, 23 Feb 2013 00:26:49 +0000</pubDate>
		<dc:creator>João Paulo</dc:creator>
				<category><![CDATA[Academia @en]]></category>
		<category><![CDATA[Bachelor]]></category>
		<category><![CDATA[Haskell @en]]></category>
		<category><![CDATA[Tech @en]]></category>

		<guid isPermaLink="false">http://joaopizani.hopto.org/?p=1877</guid>
		<description><![CDATA[Today I presented a seminar about &#8220;Functional programming and the Haskell programming language&#8221;. This presentation is part of the Seminários Individuais project at PET Computação &#8211; UFSC. I&#8217;ve talked about what is functional programming and what are its greatest features. &#8230; <a href="http://joaopizani.hopto.org/en/2009/06/haskell-fp-talk/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Today I presented a seminar about &#8220;Functional programming and the Haskell programming language&#8221;. This presentation is part of the <a href="http://pet.inf.ufsc.br/seminarios_individuais">Seminários Individuais</a> project at <a href="http://pet.inf.ufsc.br/">PET Computação &#8211; UFSC</a>.</p>
<p>I&#8217;ve talked about what is functional programming and what are its greatest features. I&#8217;ve also shown the unique characteristics of Haskell that make it not just another programming language. The current state of the Haskell development toolchain and libraries was shown, and I also gave some directions about downloads, books and good tutorials for those interested in learning Haskell.</p>
<p>It&#8217;s always nice talking about something you like :) I already posted here in the blog another  [intlink id="155" type="post"]article[/intlink] with some reasons to learn Haskell. The slides from the presentation are available here:  <a rel="attachment wp-att-189" href="http://joaopizani.hopto.org/2009/06/haskell-fp-talk/seminario-haskell/">Seminar &#8211; Prog. Funcional e Haskell (in portuguese)</a></p>
 <p><a href="http://joaopizani.hopto.org/?flattrss_redirect&amp;id=1877&amp;md5=9066baf03ce29ddb92bcfbb44366335d" title="Flattr" target="_blank"><img src="http://joaopizani.hopto.org/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://joaopizani.hopto.org/en/2009/06/haskell-fp-talk/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=joaopizani&amp;popout=1&amp;url=http%3A%2F%2Fjoaopizani.hopto.org%2Fen%2F2009%2F06%2Fhaskell-fp-talk%2F&amp;language=en_GB&amp;category=text&amp;title=Seminar+presentation+on+Functional+Programming+and+Haskell&amp;description=Today+I+presented+a+seminar+about+%26%238220%3BFunctional+programming+and+the+Haskell+programming+language%26%238221%3B.+This+presentation+is+part+of+the+Semin%C3%A1rios+Individuais+project+at+PET+Computa%C3%A7%C3%A3o+%26%238211%3B+UFSC.+I%26%238217%3Bve+talked+about...&amp;tags=blog" type="text/html" />
	</item>
	</channel>
</rss>
