<?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>coder . cl &#187; haskell</title>
	<atom:link href="http://coder.cl/category/programming/haskell/feed/" rel="self" type="application/rss+xml" />
	<link>http://coder.cl</link>
	<description>web developer &#38; system programmer</description>
	<lastBuildDate>Tue, 15 May 2012 10:46:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>my software design principles</title>
		<link>http://coder.cl/2012/05/my-software-design-principles/</link>
		<comments>http://coder.cl/2012/05/my-software-design-principles/#comments</comments>
		<pubDate>Sat, 05 May 2012 12:35:17 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2448</guid>
		<description><![CDATA[Most modern applications are providing APIs. That allows you to integrate those applications providing APIs with third party applications and create a real cloud computing environment. From an architectural perspective, we should have at least to have in mind the architectural pattern to be used, design patterns to be implemented, the protocol to use and [...]]]></description>
			<content:encoded><![CDATA[<p>Most modern applications are providing APIs. That allows you to integrate those applications providing APIs with third party applications and create a real <i>cloud</i> computing environment. From an architectural perspective, we should have at least to have in mind the architectural pattern to be used, design patterns to be implemented, the protocol to use and the data format to expose the API. The architectural pattern should be simple, the design pattern efficient, the protocol lightweight and the data format flexible for your requirements. With a good API design, it should be stable enough to support changes along the time dynamically.</p>
<p><span id="more-2448"></span></p>
<p>The architectural pattern should be simple. Most people is thinking on the MVC architectural pattern as the most proper architectural for any application. But really the MVC pattern was designed with very old basis and mostly with the idea of generalizing the user interface of desktop applications. Currently, Web Applications are build on top of many technologies, not RDBMS engines only, so you should start using the proper architectural pattern, where technology diversity should follow the maximum cohesion principle, rather than coupling application components.</p>
<p>We have as key principle of design <i>&laquo;minimum coupling, maximum cohesion&raquo;</i>, but I would like to add <i>&laquo;proper generalization&raquo;</i>. So, finally we should have <i>&laquo;minimum coupling, maximum cohesion &amp; proper generalization&raquo;</i> as design basis. If we observe, generalizations are older than software, we can stage that the term comes from Maths, where a generalization is a concept that can be applied to multiple problems and solve them using that concept. Cohesion is the principle of independent components that can work together, and coupling is a design which cannot separate its components. One of the best and classical examples of maximum cohesion on its design is Unix, where there are many small tools that can work together without coupling its functionalities.</p>
<p>A good generalization comes with from a good model, and any good generalization usually is able to solve multiple problems at once. Object Oriented programming provides a rich interface for abstractions, where the generalization is one of the most powerful ones, but in words of real generalization, I can proudly say that Monads are one of the best abstractions and mostly generalization that I ever seen.</p>
<ul>
<li>Haskell Programmer: Hey Java programmer, you know how just about everything is represented by a class?</li>
<li>Java Programmer: Yea&#8230;</li>
<li>HP: Even stuff no business being a class</li>
<li>JP: Well, it is our fundamental abstraction for anything larger than a function. It may be clumsy, but it can be used to implement any other design pattern we need.</li>
<li>HP: Well Monads serve the same role for us.</li>
<li>JP: Nulls?</li>
<li>HP: Maybe Monad</li>
<li>JP: I/O?</li>
<li>HP: IO Monad</li>
<li>JP: Exceptions and error handling?</li>
<li>HP: We have several ways, but mostly Maybe Monad</li>
<li>JP: List comprehension?</li>
<li>HP: Again, Monads</li>
<li>JP: Mutable data structures?</li>
<li>HP: That would be the State Monad<sub><a href="#note_2">[2]</a></sub></li>
</ul>
<p>With the proper generalization you can make your design to be consistent, robust and reliable. But you must leave the generalization concept just as <i>hierarchy</i> problem. It should be stated globally as <i>computational</i> problem rather than design problem only. A generalization as computation can be applied to multiple problems, where applying computational generalizations we can find mapping functions that can be globally used. This can be reached combining the IPO model and Object Oriented models properly, working together.</p>
<p>Software design is not easy. An UML class model is not enough, where it can only display <i>structures</i>, probably with a sequence models and communication models you can reach a good IPO design, but not without the proper knowledge about the implementation. So, any <i>analyst</i> who does not <a href='http://programming-motherfucker.com/' title='Programming, Motherfucker!, Do you speak it?'>knows how to program</a>, is just wasting your <a href='http://www.lnds.net/blog/2012/04/programa-ctm.html' title='¡Programa CTM!'>money and time</a>, with the obvious further reimplementation and redesign of the software product.</p>
<p>And you should start adding the proper generalizations as computations to your design, working together with your hierarchical generalizations, so they can bring you the proper quality along the time.</p>
<p style="font-size:10pt;"><a name="note_2">[2]</a> This is an excerpt from a discussion on a programming forum.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/05/my-software-design-principles/">Permalink</a> |
<a href="http://coder.cl/2012/05/my-software-design-principles/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/05/my-software-design-principles/&title=my software design principles">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/05/my-software-design-principles/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>how important is to optimize haskell code?</title>
		<link>http://coder.cl/2012/05/how-important-is-to-optimize-haskell-code/</link>
		<comments>http://coder.cl/2012/05/how-important-is-to-optimize-haskell-code/#comments</comments>
		<pubDate>Wed, 02 May 2012 14:36:11 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2419</guid>
		<description><![CDATA[Programming in Haskell is cool. You have various functions and abstractions to work with. But it has several considerations to have in mind once you are programming in this language. The main one about its performance and memory usage &#8212; in my opinion &#8212; is where to place lazy evaluated expressions and where to place [...]]]></description>
			<content:encoded><![CDATA[<p>Programming in Haskell is cool. You have various functions and abstractions to work with. But it has several considerations to have in mind once you are programming in this language. The main one about its performance and memory usage &mdash; in my opinion &mdash; is where to place lazy evaluated expressions and where to place strictly evaluated expressions. There are various articles with very good recommendations, but I want to show you a practical example, where you can see how effectively is used the lazy evaluation and released in a good execution point of the example program.</p>
<p><span id="more-2419"></span></p>
<p>As you know I am currently solving the <a href='http://projecteuler.net/' title='Project Euler'>Project Euler</a> problem set, just as toy project, to practice some Haskell code with some not so complex problems. And yesterday I have implemented the solution for the <a href='http://projecteuler.net/problem=104' title='Project Euler: Problem 104'>problem 104</a>, which is trying to find first pandigital digits from 1 to 9 on the last and first digits of a Fibonacci number. So, the Fibonacci should have more than 9 digits to solve this problem. You can see the code of the solution on <a href='https://github.com/dmw/prjeuler/blob/master/src/problem104.hs' title='Project Euler in Haskell: Solution 104'>this link</a>.</p>
<p>If you observe the code, you will see that it is respecting the Haskell tail call convention, where you must use closures to ensure that the compiled code will be using guarded recursions. Otherwise the functions will become standard recursive functions, rather being compiled as guarded recursions &mdash; which are similar to tail calls.</p>
<pre name="code" class="brush:haskell;">

-- | Calculates the Fibonacci Term N
fib :: Int                      -- ^ Term to calculate.
       -> Integer               -- ^ Fibonacci Term as Result.
fib n = snd . foldl' fib' (1, 0) . dropWhile not $
        [testBit n k | k < - let s = bitSize n in [s - 1, s - 2 .. 0]]
  where
    fib' (f, g) p
      | p         = (f * (f + 2 * g), ss)
      | otherwise = (ss, g * (2 * f - g))
      where ss = f * f + g * g
</pre>
<p>Also it defines two functions to check if the number meets the pandigital requirement, where <tt>isValidDig</tt> is not called immediately from the <tt>checkRange</tt> recursive function, instead of calling that function, it calls the <tt>isValidPan</tt> function, where it is called with the constant expression <tt>[1..9]</tt>, avoiding consecutive List instantiation, and using <tt>`seq`</tt> to avoid lazy evaluations and further stack overloading.</p>
</pre>
<pre name="code" class="brush:haskell;">

-- | Checks if the given number x have valid last n digits
-- and last n digits
isValidDig :: Integer           -- ^ Number to Check.
              -&gt; [Integer]      -- ^ Sequence to Check.
              -&gt; Bool           -- ^ Is valid or not.
isValidDig x xs
  | length (digits 10 x) &lt; length xs = False
  | otherwise = let ds = digits 10 x
                    l = length xs
                    s = sort xs
                    r = sort $ take l ds
                    t = sort $ take l $ reverse ds
                in r == s &amp;&amp; t == s

-- | Checks sequentially if the given range covers the
-- problem of pandigital sequence of digits using the reqDigs
-- sequence.
isValidPan :: Int               -- ^ Number to check.
              -&gt; Bool           -- ^ True when is valid.
isValidPan x = r `seq` isValidDig r [1..9]
               where r = fib x
</pre>
<p>This allows the usage of a small stack space once it is called, due to strict evaluation, where all List instances are not kept in memory, and similar structures are only evaluated once, without keeping that memory in use, and being released once those non recursive functions are finished. Finally we can use <tt>isValidPan</tt> on a guard, without the risk of overloading the stack.</p>
<pre name="code" class="brush:haskell;">

-- | Checks sequentially if the given range covers the
-- problem of pandigital problem.
checkRange :: Int                   -- ^ Starting number.
              -&gt; Int                -- ^ End number
              -&gt; Int                -- ^ Returning Number (-1 on failure).
checkRange m n = sCheckRange m n m
  where sCheckRange x y z
          | z &gt;= y = -1
          | isValidPan z = z
          | otherwise = let r = z + 1
                        in r `seq` sCheckRange x y r
</pre>
<p>The closure used on the <tt>checkRange</tt> function makes the compiler to start using the tail call as it is required by this kind of functions where you must keep very well controlled the evaluation of the program expressions. Any mistake on the evaluation of the program will lead you to use more memory that it is really required, leading to slowness and delayed evaluations where your code could crash with stack overflows.</p>
<div class="figure">
<a href="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/problem104.bin_1.png" title="Problem 104 Example Memory Usage" target="_blank"><img src="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/problem104.bin_1.png" border="0" alt="Problem 104 Example Memory Usage"/></a></p>
<div>Problem 104 Example Memory Usage</div>
</div>
<p>As you see on the cost centre chart above, the program is using almost a constant amount of memory along its execution, evaluating Fibonacci terms from 1000 to 9000, in 12 seconds approximately. So, the keys of a good memory usage in Haskell is to use evaluation expressions and guarded recursions properly.</p>
<p>Another example is the problem #255 in the Project Euler. This code is using Haskell tail calls to ensure the optimal memory allocation. For example the function used to calculate the rounded square root using the Heron Operation as follows.</p>
<pre name="code" class="brush:haskell;">
-- | Applies the Heron Operation recursively until it returns
-- the round square root and the number of iterations as tuple.
heronOpRec :: Integer                 -- ^ Heron Operation to Apply
           -&gt; (Integer, Integer)      -- ^ Pair (RSR, Iterations)
heronOpRec a = heronOp a a (digitBase $ numDigits a) 0
  where heronOp o n m a
          | o == 0 = (0, 0)
          | o == 1 = (1, 1)
          | o == 2 = (1, 1)
          | o == 3 = (2, 1)
          | n == m = (m, a)
          | otherwise = let x = fromIntegral m
                            y = fromIntegral o / x
                            s = round ((x + y) / 2)
                            t = a + 1
                        in heronOp o m s t
</pre>
<p>And the application of this kind of recursive calls can be seen in the following chart.</p>
<div class="figure">
<a href="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/problem255.bin_.png" title="Problem 255 Example Memory Usage" target="_blank"><img src="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/problem255.bin_.png" border="0" alt="Problem 255 Example Memory Usage"/></a></p>
<div>Problem 255 Example Memory Usage</div>
</div>
<p>If you compare both charts and see how both problem solutions are programmed, you will see that they keep a very low limit on memory usage. The <a href='https://github.com/dmw/prjeuler/blob/master/src/problem255.hs' title='Project Euler: Problem #255'>problem #255</a> is using numbers purely, and where <a href='https://github.com/dmw/prjeuler/blob/master/src/problem104.hs' title='Project Euler: Problem #104'>problem #104</a> solution is using lists to hold the digits of the number to be checked as pandigital, that is why it has some peaks on the <tt>isValidDig</tt> function, but once the program exits that function that memory is deallocated by the garbage collector.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/05/how-important-is-to-optimize-haskell-code/">Permalink</a> |
<a href="http://coder.cl/2012/05/how-important-is-to-optimize-haskell-code/#comments">One comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/05/how-important-is-to-optimize-haskell-code/&title=how important is to optimize haskell code?">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/05/how-important-is-to-optimize-haskell-code/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>project euler: problem 102</title>
		<link>http://coder.cl/2012/04/project-euler-problem-102/</link>
		<comments>http://coder.cl/2012/04/project-euler-problem-102/#comments</comments>
		<pubDate>Fri, 20 Apr 2012 10:38:11 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2392</guid>
		<description><![CDATA[I have started my own solutions to the Project Euler in Haskell. Just to practice Haskell and its features. The past problem was the problem 255. Now I have solved the problem 102, using some additional features, not taking the problem as it comes in the Project Euler. Rather than doing a simple solution in [...]]]></description>
			<content:encoded><![CDATA[<p>I have started my own solutions to the Project Euler in Haskell. Just to practice Haskell and its features. The past problem was the problem 255. Now I have solved the problem 102, using some additional features, not taking the problem as it comes in the Project Euler. Rather than doing a simple solution in plain text, I have created a program which renders the triangles in the problem using OpenGL, placing the triangles in a Windows rather than just indicating the number of triangles.</p>
<p><span id="more-2392"></span></p>
<p>Is nice to work with Haskell, you may know that you can work with a very wide variety of technologies in Haskell. Also, the Glasgow Haskell Compiler or GHC, is able to compile machine byte code, creating native executables for its runtime. Since all Project Euler problems are very nice to solve, I have created a <a href='https://github.com/dmw/prjeuler' title='dmw/prjeuler'>github repository</a> with my solutions, to share them, probably you can use them to examine some Haskell code and see if you want to learn it.</p>
<p>The problem 102 is related to triangles and point positions, and it can be seen in <a href='http://projecteuler.net/problem=102' title='Project Euler: Problem 102.'>this link</a>. The main goal of the problem is to indicate the number of triangles which are containing the origin or point <img src='http://s.wordpress.com/latex.php?latex=p%280%2C%200%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='p(0, 0)' title='p(0, 0)' class='latex' />, where I have used the <a href='http://en.wikipedia.org/wiki/Cross_product' title='Cross Product'>Cross Product</a> to solve this problem.</p>
<p>First I have defined plane points and triangles as data types in Haskell, deriving the <tt>Num</tt> type class instance on the <tt>LPt</tt> data type which represents a point in a two dimensional space.</p>
<pre name="code" class="brush:haskell;">

data LPt = LPt (Int, Int)
         deriving (Eq, Show, Ord)

data LTrg = LTrg {
  tA        :: LPt
  , tB      :: LPt
  , tC      :: LPt
  } deriving (Eq, Show, Ord)

instance Num LPt where
  x + y = LPt (fstp x + fstp y, sndp x + sndp y)

  x - y = LPt (fstp x - fstp y, sndp x - sndp y)

  x * y = LPt (fstp x * fstp y, sndp x * sndp y)

  abs x = LPt (abs (fstp x), abs (sndp x))

  fromInteger x = LPt (fromInteger x, fromInteger x)

  signum x | fstp x &lt; 0 &amp;&amp; sndp x &lt; 0 = -1
  signum x | fstp x &gt; 0 &amp;&amp; sndp x &gt; 0 = 1
  signum x = 0

crossPt :: LPt -> LPt -> LPt
crossPt x y = LPt (0, fstp x * sndp y - sndp x * fstp y)
</pre>
<p>Then is easy to reach the solution. Where I have plain text file parsing triangle points using the following functions.</p>
<pre name="code" class="brush:haskell;">

mkTriangle :: String -&gt; LTrg
mkTriangle s = LTrg { tA = head g, tB = g !! 1, tC = last g }
               where g = fmap (\x -&gt; LPt (head x, last x) )
                         $ splitEvery 2 ln
                     ln = fmap (read . strip) $ splitOn "," s

mkTriangles :: String -&gt; Int -&gt; Int -&gt; [LTrg]
mkTriangles s l h = drop l
                    $ take h
                    $ fmap mkTriangle
                    $ filter (\ x -&gt; length x &gt; 0 )
                    $ fmap strip
                    $ lines s
</pre>
<p>So, my solution do not creates all triangles on the file, rather than creating all triangles, it just takes a given segment of the file, and renders their position in the OpenGL windows.</p>
<pre name="code" class="brush:haskell;">

trgColor :: LTrg -&gt; IO ()
trgColor xs | trgContained zeroPt xs = colorCyan
trgColor xs = colorGreen

displayTriangle :: LTrg -&gt; IO ()
displayTriangle xs = do _ &lt;- renderPrimitive Polygon $ do
                          trgColor xs
                          mapM ptToGlPt [tA xs, tB xs, tC xs]
                        flush

displayTriangles :: [LTrg] -&gt; F.Font -&gt; IO ()
displayTriangles xs f = do clear [ ColorBuffer, DepthBuffer ]
                           mapM_ displayTriangle xs
                           trgTextCont xs f
                           flush
</pre>
<p>Where the call to the <tt>trgContained</tt> in the guard at the <tt>trgColor</tt> function is what indicates if the triangle contains or not the point <img src='http://s.wordpress.com/latex.php?latex=p%280%2C%200%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='p(0, 0)' title='p(0, 0)' class='latex' /> or zeroPt. So, you can see two sample results as follows.</p>
<div class="figure">
<a href="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/prjeuler-problem-102-sample-1.jpg" title="Project Euler: Problem 102 Visualization" target="_blank"><img src="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/prjeuler-problem-102-sample-1.jpg" border="0" alt="Project Euler: Problem 102 Visualization"/></a></p>
<div>Project Euler: Problem 102 Visualization Sample 1</div>
<div>./problem102 triangles.txt 70 90</div>
</div>
<div class="figure">
<a href="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/prjeuler-problem-102-sample-2.jpg" title="Project Euler: Problem 102 Visualization" target="_blank"><img src="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/prjeuler-problem-102-sample-2.jpg" border="0" alt="Project Euler: Problem 102 Visualization"/></a></p>
<div>Project Euler: Problem 102 Visualization Sample 2</div>
<div>./problem102 triangles.txt 23 48</div>
</div>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/04/project-euler-problem-102/">Permalink</a> |
<a href="http://coder.cl/2012/04/project-euler-problem-102/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/04/project-euler-problem-102/&title=project euler: problem 102">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/04/project-euler-problem-102/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>project euler: problem 255</title>
		<link>http://coder.cl/2012/04/project-euler-problem-255/</link>
		<comments>http://coder.cl/2012/04/project-euler-problem-255/#comments</comments>
		<pubDate>Sat, 14 Apr 2012 13:41:14 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2384</guid>
		<description><![CDATA[Haskell is a fabulous language, there is no looping instruction like for or while, everything is stated using recursions, like any other functional language does, preventing states across the execution, as it was defined on the computational model of most functional languages, which is known as &#955;-Calculus. There is no state, only purely functional state-less [...]]]></description>
			<content:encoded><![CDATA[<p>Haskell is a fabulous language, there is no looping instruction like <tt>for</tt> or <tt>while</tt>, everything is stated using recursions, like any other functional language does, preventing states across the execution, as it was defined on the computational model of most functional languages, which is known as <i>&lambda;-Calculus</i>. There is no state, only purely functional state-less execution paths. The <a href='http://projecteuler.net/problem=255' title='Project Euler: Problem 255'>Problem 255</a> on the <a href='http://projecteuler.net/' title='Problem 255'>Project Euler</a>, is related to rounded squares and the Heron&#8217;s method to calculate it, so I have implemented a Haskell program with that algorithm, which is obviously a recursive algorithm.</p>
<p><span id="more-2384"></span></p>
<p>If we see my solution, there is a function pair to solve the problem where <tt>heronOp</tt> is the main recursive function to solve the iterations, avoiding state. On Haskell, thanks to its main functional abstraction called Monad, you can implement state machines and similar tasks using the <a href='http://www.haskell.org/haskellwiki/State_Monad' title='Haskell: State Monad'>State Monad</a>, but states are not really required to solve anything in Haskell.</p>
<pre name="code" class="brush:haskell;">

module Main (main) where

import Data.Digits (digits)
import System.Environment (getArgs)

digitBase :: Int -&gt; Int
digitBase n | odd n = round ((2 * 10) ** ((fromIntegral n - 1) / 2))
digitBase n = round ((7 * 10) ** ((fromIntegral n - 2) / 2))

heronOp :: Int -&gt; Int -&gt; Int -&gt; Int
heronOp o n m | n == m = m
heronOp o n m = heronOp o m (round ((x + y) / 2))
                where x = fromIntegral m
                      y = fromIntegral o / x

main :: IO ()
main = do [x] &lt;- getArgs
          print
            $ heronOp (read x) (read x)
            $ digitBase $ length $ digits (read x) 10
</pre>
<p>There is &mdash; among other interesting approaches &mdash; a paper where the authors are writing about writing operating systems entirely in Haskell [<i>&laquo;A principled approach to operating system construction in Haskell&raquo;</i>], despite it is a functional language, it has solved the stack usage problems along recursive calls using <a href='http://en.wikipedia.org/wiki/Tail_call' title='Tail Call'>tail calls</a>, so you do not need to worry about recursion in almost all code, you just need to make your recursive calls lazy enough to ensure a good stack usage.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/04/project-euler-problem-255/">Permalink</a> |
<a href="http://coder.cl/2012/04/project-euler-problem-255/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/04/project-euler-problem-255/&title=project euler: problem 255">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/04/project-euler-problem-255/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>collatz problem and haskell</title>
		<link>http://coder.cl/2012/04/collatz-problem-and-haskell/</link>
		<comments>http://coder.cl/2012/04/collatz-problem-and-haskell/#comments</comments>
		<pubDate>Wed, 11 Apr 2012 23:34:12 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2378</guid>
		<description><![CDATA[The Collatz problem is Math problem related to a pair of operations which applied recursively will make a number reach 1 always. &#171;The Collatz conjecture is a conjecture in mathematics named after Lothar Collatz, who first proposed it in 1937. The conjecture is also known as the 3n + 1 conjecture, the Ulam conjecture (after [...]]]></description>
			<content:encoded><![CDATA[<p>The Collatz problem is Math problem related to a pair of operations which applied recursively will make a number reach 1 always. <i>&laquo;The Collatz conjecture is a conjecture in mathematics named after Lothar Collatz, who first proposed it in 1937. The conjecture is also known as the 3n + 1 conjecture, the Ulam conjecture (after Stanisław Ulam), Kakutani&#8217;s problem (after Shizuo Kakutani), the Thwaites conjecture (after Sir Bryan Thwaites), Hasse&#8217;s algorithm (after Helmut Hasse), or the Syracuse problem; the sequence of numbers involved is referred to as the hailstone sequence or hailstone numbers, or as wondrous numbers.&raquo;</i></p>
<blockquote><p>
Take any natural number n. If n is even, divide it by 2 to get n / 2. If n is odd, multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process (which has been called &#8220;Half Or Triple Plus One&#8221;, or HOTPO[4]) indefinitely. The conjecture is that no matter what number you start with, you will always eventually reach 1. The property has also been called oneness.
</p></blockquote>
<p><span id="more-2378"></span></p>
<p>It was proposed as problem as part of the <a href='http://projecteuler.net/' title='Project Euler'>Project Euler</a> and by <a href='http://www.programando.org/blog/2012/04/desafio-2012-04-el-problema-de-siracusa/' title='La Sombra de Dijkstra: Desafío 2012-04: El problema de Siracusa'>Eduardo Díaz on his blog</a>, I have implemented my solution in Haskell, because I want to enhance my skills with this language, to reach the most professional coding on it.</p>
<p>My first solution is as follows, is using recursion and <tt>if</tt> statements. Where <tt>if</tt> statements should be avoided, also the <tt>colmax</tt> function can be reduced and eliminated.</p>
<pre name="code" class="brush:haskell;">

module Main (main) where

import System.Environment

collatz :: Int -&gt; [Int] -&gt; [Int]
collatz 1 xs = xs ++ [1]
collatz n xs = if even n
                  then collatz (n `div` 2) $ xs ++ [n]
               else collatz (n * 3 + 1) $ xs ++ [n]

colmax :: [Int] -&gt; Int -&gt; Int -&gt; Int
colmax [] _ m = m
colmax (x:xs) n m = let r = length $ collatz x []
                        in if r &gt; n
                              then colmax xs r x
                           else colmax xs n m

main :: IO ()
main = do [x] &lt;- getArgs
          print $ colmax [1..(read x)] 0 0
</pre>
<p>My second solution uses the Haskell features to avoid <tt>if</tt> statements and some reductions to allow more concise code, mainly due to the lazyness of used functions.</p>
<pre name="code" class="brush:haskell;">

module Main (main) where

import System.Environment
import Data.List
import Data.Ord
import Data.Function

collatz :: Int -&gt; [Int] -&gt; [Int]
collatz n xs | n == 1 = xs ++ [1]
             | even n = collatz (n `div` 2) $ xs ++ [n]
             | otherwise = collatz (n * 3 + 1) $ xs ++ [n]

main :: IO ()
main = do [x] &lt;- getArgs
          print $ fst $ maximumBy (comparing length `on` snd)
            $ fmap (\ x -&gt; (x, collatz x []) ) [1..(read x)]
</pre>
<p>This code looks really well, and seems to be more clear to understand, mainly due to the inline pointfree lambda expression <tt>comparing length `on` snd</tt>. So, the code is easy to understand and clear enough. Without <tt>if</tt> statements and using guards rather than <tt>if</tt>.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/04/collatz-problem-and-haskell/">Permalink</a> |
<a href="http://coder.cl/2012/04/collatz-problem-and-haskell/#comments">One comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/04/collatz-problem-and-haskell/&title=collatz problem and haskell">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/04/collatz-problem-and-haskell/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>memory usage in haskell</title>
		<link>http://coder.cl/2012/03/memory-usage-in-haskell/</link>
		<comments>http://coder.cl/2012/03/memory-usage-in-haskell/#comments</comments>
		<pubDate>Wed, 21 Mar 2012 21:17:07 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[logrev]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2341</guid>
		<description><![CDATA[As you I am a Haskell programmer. I have started a FOSS project called Apache Log Reviser, or logrev as short name. I have been playing with code optimizations in Haskell on that project. So, I want to share some experience and considerations regarding its memory usage, mainly on what is related to lazy evaluations [...]]]></description>
			<content:encoded><![CDATA[<p>As you I am a Haskell programmer. I have started a FOSS project called <a href='https://github.com/dmw/ApacheLogRev' title='Apache Log Reviser' target="_blank">Apache Log Reviser</a>, or <a href='https://github.com/dmw/ApacheLogRev' title='Apache Log Reviser' target="_blank">logrev</a> as short name. I have been playing with code optimizations in Haskell on that project. So, I want to share some experience and considerations regarding its memory usage, mainly on what is related to lazy evaluations and non-strict bindings. Where lazy evaluations should be used every time you need to read or write data with delayed behaviour, for example reading large lists or even lazy lists, and non-strict bindings should be used every time you need to request data to be placed on memory for immediate reading or writing.</p>
<p><span id="more-2341"></span></p>
<p>I have replaced the main file processing loop &mdash; the one that is collecting data from log lines &mdash; forcing lazy evaluations and non-strict bindings where they are required. The resulting code after the optimization is as follows.</p>
<pre name="code" class="brush:haskell;">

foldLogLines :: LogRevStatsMap
                -&gt; LogRevOptions
                -&gt; [String]
                -&gt; LogRevStatsMap
foldLogLines ms _ [] = ms
foldLogLines ms o ~ls = fll ms ls
                        where fll rs [] = rs
                              fll rs (x : ~xs) = let
                                lm = parseLogLine x
                                ns = lm `seq` o `seq` procLogMachine o rs lm
                                in seq ns $ fll ns xs
</pre>
<p>Again I am using <tt>seq</tt> for non-strict bindings but now I made the lines argument pattern entirely lazy, including the constructs inside the closure which brings even more laziness to the folding functions. The original optimization was just an implementation of a left folding functions, now it works using the same left folding function using a closure which uses lazy reads of the given list of strings &mdash; or log lines. As you remember the first chart obtained was using about ~33MB of memory, as follows.</p>
<div class="figure">
<a href="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/03/initial-logrev-profiling.png" title="ApacheLogRev with Initial Optimization" target="_blank"><img src="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/03/initial-logrev-profiling.png" border="0" alt="ApacheLogRev with Initial Optimization"/></a></p>
<div>ApacheLogRev with Initial Optimization</div>
</div>
<p><center>&lambda;<sup>&lambda;</sup>&lambda;</center></p>
<p>With the second optimization, the resulting memory usage has been reduced to ~13MB. Despite the <tt>readFile</tt> and <tt>lines</tt> functions are lazy, we must implement function with the same lazy behaviour, and we must use non-strict bindings only where we need immediate access to the data. Also, you should know that <tt>let</tt> and <tt>where</tt> statements have non-strict bindings for their variables, so they are placed immediately on the heap, unless you declare them lazy explicitly. The resulting profiling chart of the second optimization is as follows.</p>
<div class="figure">
<a href="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/03/lazy-logrev-profiling.png" title="ApacheLogRev with Lazy Reading" target="_blank"><img src="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/03/lazy-logrev-profiling.png" border="0" alt="ApacheLogRev with Lazy Reading"/></a></p>
<div>ApacheLogRev with Lazy Reading</div>
</div>
<p>Finally I have concluded that we must not underestimate the power of lazy evaluations and Haskell patterns. Once they are used properly, you gain very good performance and optimal memory usage. Enjoy Haskell as programming language.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/03/memory-usage-in-haskell/">Permalink</a> |
<a href="http://coder.cl/2012/03/memory-usage-in-haskell/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/03/memory-usage-in-haskell/&title=memory usage in haskell">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/03/memory-usage-in-haskell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>a good start on logrev</title>
		<link>http://coder.cl/2012/03/a-good-start-on-logrev/</link>
		<comments>http://coder.cl/2012/03/a-good-start-on-logrev/#comments</comments>
		<pubDate>Sat, 17 Mar 2012 12:43:36 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[logrev]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[projects]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2328</guid>
		<description><![CDATA[As you know ApacheLogRev or logrev as short name, is my first Haskell FOSS project &#8212; I have other FOSS projects written in C and Python &#8212; and I want to share some experiences about logrev while I was developing some features that it should have in the future, because it is still under development [...]]]></description>
			<content:encoded><![CDATA[<p>As you know ApacheLogRev or <i>logrev</i> as short name, is my first Haskell FOSS project &mdash; I have other FOSS projects written in C and Python &mdash; and I want to share some experiences about logrev while I was developing some features that it should have in the future, because it is still under development and it is not finished yet. Basically, it is using the Parsec combinator based parser. One of the best advantages of this parser builder is the fact that it is generating parsers on run time, rather than creating fixed parsers using BNF grammars which are subject of static context free processing, rather than creating dynamic parsers.</p>
<p><span id="more-2328"></span></p>
<p>Parsec allows you to create a parser dynamically on runtime, rather than compiling a parser specification and grammar specification on compile time as being done with <i>flex</i> and <i>bison</i>. As combinatorial construct, seems that can write a dynamic compiler generated in run time, instead of having a compiler built as static component which cannot be modified in run time &mdash; with some exception that are not covered by <i>flex</i> and <i>bison</i>, like any C++ compiler, which is capable to understand a small subset of syntax sugar enabled features like templates and operators.</p>
<p>I have created a DSL called <i>Log Reviser Specification</i> or <i>LSR</i> as short name which allows you to create log processing statements defining variables, processing functions and specify a reports based on the collected data. You can see the LSR parser on the <a href='https://github.com/dmw/ApacheLogRev/blob/master/src/Proc/LRS/Parser.hs' title='ApacheLogRev Repository' target="_blank">github repository</a> and a <a href='https://github.com/dmw/ApacheLogRev/blob/master/main.lrs' title='Sample LSR File for Apache Access Log' target="_blank">sample LSR</a> file on the same repository.</p>
<p><center>&lambda; <sup>&lambda;</sup> &lambda;</center></p>
<p>The problem of memory leaks &mdash; which is present on <strong>all</strong> languages, without exception &mdash; had come to my mind once the program was not able to parse a huge file without crashing. The fact that every language can be subject of memory leaks, is so real as the fact that you cannot abuse of recursion in procedural and object oriented languages. So, I have started profiling the application. With the initial revision, I got <tt>LogLine</tt> data type being instantiated many times without deallocation, with many instances which were kept in memory due to the lazy evaluation behaviour which is natural in Haskell. Tracing its memory usage, I got the following chart.</p>
<div class="figure">
<a href="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/03/logrev-profile-chart-mm.png" title="ApacheLogRev with Memory Leaks" target="_blank"><img src="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/03/logrev-profile-chart-mm.png" border="0" alt="ApacheLogRev with Memory Leaks"/></a></p>
<div>ApacheLogRev with Memory Leaks</div>
</div>
<p>The program execution was keeping a peak of LogLine instances on memory without being released due to Haskell lazy evaluation. So, now I am using <a href='http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:seq' title='seq :: a -&gt; b -&gt; b'>seq</a> and <a href='http://hackage.haskell.org/packages/archive/deepseq/1.3.0.0/doc/html/Control-DeepSeq.html#v:deepseq' title='deepseq :: NFData a =&gt; a -&gt; b -&gt; b'>deepseq</a> to reduce the amount lazy evaluations made in Haskell.</p>
<pre name="code" class="brush:haskell;">

instance NFData LogLine where
  rnf a = a `seq` ()

parseLogLine :: String -&gt; Maybe LogLine
parseLogLine s = let
  r = parse logLine &quot;[Invalid]&quot; s
  in case r of
          Left  _   -&gt; Nothing
          Right itm -&gt; itm `deepseq` Just itm

foldLogLines :: [LogRevStatsAction]
                -&gt; LogRevOptions
                -&gt; [String]
                -&gt; [LogRevStatsAction]
foldLogLines [] _ [] = []
foldLogLines ms _ [] = ms
foldLogLines ms o (x : xs) = let
  lm :: Maybe LogLine
  ns :: [LogRevStatsAction]
  lm = x `seq` parseLogLine x
  ns = lm `seq` o `seq` procLogMachine o ms lm
  in foldLogLines ns o xs
</pre>
<p>I have replaced the initial folding function &mdash; where it was using <tt>fmap</tt> and <tt>hGetLine</tt> &mdash; with the lazy evaluation function <tt>hGetContents</tt> for file descriptor reading and strict function for result processing <tt>foldLogLines</tt>. So, for file reading currently I am using lazy reads, but strict evaluation for line processing, allowing large file processing with very good results, thanks to the <i>left folded</i> strict evaluation of the lazy file reading. So we can appreciate the difference in the following chart.</p>
<div class="figure">
<a href="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/03/logrev-profile-chart-nm.png" title="ApacheLogRev without Memory Leaks" target="_blank"><img src="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/03/logrev-profile-chart-nm.png" border="0" alt="ApacheLogRev without Memory Leaks"/></a></p>
<div>ApacheLogRev without Memory Leaks</div>
</div>
<p><center>&lambda; <sup>&lambda;</sup> &lambda;</center></p>
<p>So, the garbage collector is really being used without keeping references on memory and instances linked to past results thanks to the tail call implementation in GHC, where we get an initial peak of memory usage which is being reduced along the execution. Also, if you have reached the <a href='http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/OutOfMemoryError.html' title='OutOfMemoryError'>Java OutOfMemoryError</a>, <a href='http://msdn.microsoft.com/en-us/library/system.outofmemoryexception.aspx' title='OutOfMemoryException'>.NET OutOfMemoryException</a>, <i>&laquo;PHP Allowed Memory Size Exhausted Fatal Error&raquo;</i>, and similar ones in your favorite language, and your solution is to increase the memory limits, <strong>your are doing it wrong</strong>. The fact that you have memory leaks in your code and you must correct the memory leaks rather than increasing the memory limits, just is telling me that you do not have any idea about memory management. Despite many languages now are using garbage collectors.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/03/a-good-start-on-logrev/">Permalink</a> |
<a href="http://coder.cl/2012/03/a-good-start-on-logrev/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/03/a-good-start-on-logrev/&title=a good start on logrev">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/03/a-good-start-on-logrev/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>haskell and emacs</title>
		<link>http://coder.cl/2012/02/haskell-and-emacs/</link>
		<comments>http://coder.cl/2012/02/haskell-and-emacs/#comments</comments>
		<pubDate>Mon, 20 Feb 2012 12:17:04 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[emacs]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2262</guid>
		<description><![CDATA[I think that I have a very nice integration between Haskell and Emacs. The first stuff that you should do to work with Haskell under Emacs, is to integrate the haskell-mode in Emacs with the proper hook to get the haskell-mode fully functional and working fine with Haskell code, so you can use Emacs as [...]]]></description>
			<content:encoded><![CDATA[<p>I think that I have a very nice integration between Haskell and Emacs. The first stuff that you should do to work with Haskell under Emacs, is to integrate the haskell-mode in Emacs with the proper hook to get the haskell-mode fully functional and working fine with Haskell code, so you can use Emacs as most likely an IDE rather than a simple text editor. That can be done thanks to the powerful Emacs Lisp interpreter that has embedded the Emacs editor.</p>
<p><span id="more-2262"></span></p>
<pre name="code" class="brush:lisp;">

(defun dmw-haskell-pointfree-region ()
  "Executes the Haskell pointfree too on the marked region."
  (interactive)
  (let ((pfcmd (format "pointfree %s"
                       (shell-quote-argument (buffer-substring-no-properties
                                              (region-beginning)
                                              (region-end))))))
    (message (format "%s" (shell-command-to-string pfcmd)))))

(defun dmw-haskell-pointfree-replace ()
  "Replaces the marked region with the Haskell pointfree evaluation."
  (interactive)
  (let ((pfcmd (format "pointfree %s"
                       (shell-quote-argument (buffer-substring-no-properties
                                              (region-beginning)
                                              (region-end))))))
    (shell-command-on-region (region-beginning) (region-end) pfcmd t)))

(defun dmw-haskell-hlint-buffer ()
  "Runs hlint on the currently edited file."
  (interactive)
  (set (make-local-variable 'compile-command)
       (let ((file (file-name-nondirectory buffer-file-name)))
         (format "hlint %s" file)))
  (message compile-command)
  (compile compile-command))

(defun dmw-haskell-mode-hook ()
  "Haskell Mode Hook."
  (setq haskell-program-name "/usr/bin/ghci"
        indent-tabs-mode nil)
  (turn-on-haskell-doc-mode)
  (turn-on-haskell-indentation)
  (turn-on-haskell-decl-scan)
  (capitalized-words-mode t)
  (define-key haskell-mode-map "C-cC-p" 'dmw-haskell-pointfree-region)
  (define-key haskell-mode-map "C-cC-r" 'dmw-haskell-pointfree-replace)
  (define-key haskell-mode-map "C-cC-c" 'dmw-haskell-hlint-buffer)
  (message "&gt;&gt;&gt; done dmw-haskell-mode-hook..."))
</pre>
<p>So, some nice thing about this mode-hook, is the fact that it can search for documentation on each function using <tt>C-c M-/</tt> and find definitions using <tt>C-c M-.</tt>. With two custom commands which can allow you to use <i>Pointfree</i> &mdash; which can be installed using cabal &mdash; and <i>Hlint</i> &mdash; which can be found usually under your operating system without problems and can be installed using cabal too. So, to use <i>Hlint</i> with this hook, you can start it with <tt>C-c C-c</tt> or <tt>C-c C-v</tt>, and you can see if there is a point free style replacement for the selected expression &mdash; using Emacs region selection &mdash; with the binding <tt>C-c C-p</tt>, and if you like the point free style replacement, you can replace the selected region with the point free style expression using the binding <tt>C-c C-r</tt>.</p>
<p>I will try to add more nice stuff to my Haskell hook, probably something like searching modules and ordering imports, because would be nice to have similar stuff running under Emacs, to allow more easy to handle Haskell edition under Emacs. Enjoy!</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/02/haskell-and-emacs/">Permalink</a> |
<a href="http://coder.cl/2012/02/haskell-and-emacs/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/02/haskell-and-emacs/&title=haskell and emacs">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/02/haskell-and-emacs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>challenge 2012.02.13 intermediate</title>
		<link>http://coder.cl/2012/02/challenge-2012-02-13-intermediate/</link>
		<comments>http://coder.cl/2012/02/challenge-2012-02-13-intermediate/#comments</comments>
		<pubDate>Tue, 14 Feb 2012 16:11:19 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2250</guid>
		<description><![CDATA[Here is the another combinatorics challenge with a level intermediate on the programming forum. Still I think that they are very easy to solve. Here is the solution in Haskell, where not real combinatorics are required to supply a solution, instead word elements are used as numbers to find word matches in the text file, [...]]]></description>
			<content:encoded><![CDATA[<p>Here is the another combinatorics challenge with a level <i>intermediate</i> on the programming forum. Still I think that they are very easy to solve. Here is the solution in Haskell, where not real combinatorics are required to supply a solution, instead word elements are used as numbers to find word matches in the text file, without too many libraries and lines of code.</p>
<p><span id="more-2250"></span></p>
<blockquote><p>
Your challenge today is to write a program that can find the amount of anagrams within a .txt file. For example, &#8220;snap&#8221; would be an anagram of &#8220;pans&#8221;, and &#8220;skate&#8221; would be an anagram of &#8220;stake&#8221;.
</p></blockquote>
<pre name="code" class="brush:haskell;">

module Main where

import Data.Char
import Data.List
import Data.Maybe
import Data.String.Utils
import System.Environment

liftLine :: String -&gt; [Int]
liftLine l = fmap ord $ strip l

matchWord :: [Int] -&gt; [Int] -&gt; Maybe [Int]
matchWord w1 w2 = if sort w1 == sort w2
                     then Just w2
                     else Nothing

findMatches :: [Int] -&gt; [[Int]] -&gt; [String]
findMatches x xs = fmap (fmap chr . fromJust)
                   $ filter (/= Nothing)
                   $ fmap (matchWord x) xs

main :: IO ()
main = do [n, w] &lt;- getArgs
          f &lt;- readFile n
          let words = fmap liftLine $ lines f
              wmatch = liftLine w
              in mapM_ putStrLn $ findMatches wmatch words
</pre>
<p>Where the code above can be compiled using <tt>ghc --make prog.hs -o prog</tt> or can be executed using <tt>runghc prog.hs text-file word</tt>. With the text file bellow:</p>
<pre name="code" class="brush:bash;">
snap
pans
skate
stake
takes
kates
tekas
ketas
</pre>
<p>Its output is as follows:</p>
<pre name="code" class="brush:bash;">
13:02 [dmw@www:0 exercises]$ ./challenge20120213 challenge20120213.txt kates
skate
stake
takes
kates
tekas
ketas
</pre>
<p>Enjoy&#8230;</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/02/challenge-2012-02-13-intermediate/">Permalink</a> |
<a href="http://coder.cl/2012/02/challenge-2012-02-13-intermediate/#comments">6 comments</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/02/challenge-2012-02-13-intermediate/&title=challenge 2012.02.13 intermediate">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/02/challenge-2012-02-13-intermediate/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>combinatorics problem in haskell</title>
		<link>http://coder.cl/2012/02/combinatorics-problem-in-haskell/</link>
		<comments>http://coder.cl/2012/02/combinatorics-problem-in-haskell/#comments</comments>
		<pubDate>Sun, 12 Feb 2012 20:19:52 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2238</guid>
		<description><![CDATA[Here is another challenge called difficult, but seems to be quite easy to solve. It is a simple feasible operation search algorithm between lists of numbers, so it is not so complex to solve and took few minutes to get it working on Haskell, because Haskell provides various tools to work with algorithms. Also this [...]]]></description>
			<content:encoded><![CDATA[<p>Here is another challenge called difficult, but seems to be quite easy to solve. It is a simple feasible operation search algorithm between lists of numbers, so it is not so complex to solve and took few minutes to get it working on Haskell, because Haskell provides various tools to work with algorithms. Also this solution does the extra credit, no matter if the list has up to four integers.</p>
<p><span id="more-2238"></span></p>
<blockquote>
<p>Today, your challenge is to create a program that will take a series of numbers (5, 3, 15), and find how those numbers can add, subtract, multiply, or divide in various ways to relate to each other. This string of numbers should result in 5 * 3 = 15, or 15 /3 = 5, or 15/5 = 3. When you are done, test your numbers with the following strings:</p>
<p><br/></p>
<ul>
<li>4, 2, 8</li>
<li>6, 2, 12</li>
<li>6, 2, 3</li>
<li>9, 12, 108</li>
<li>4, 16, 64</li>
</ul>
<p>For extra credit, have the program list all possible combinations.<br />
for even more extra credit, allow the program to deal with strings of greater than three numbers. For example, an input of (3, 5, 5, 3) would be 3 * 5 = 15, 15/5 = 3. When you are finished, test them with the following strings.</p>
<ul>
<li>2, 4, 6, 3</li>
<li>1, 1, 2, 3</li>
<li>4, 4, 3, 4</li>
<li>8, 4, 3, 6</li>
<li>9, 3, 1, 7</li>
</ul>
</blockquote>
<p>Here is the full solution in Haskell, just to practice a little. Compile it using <tt>ghc --make prog.hs -o prog</tt> or run it using <tt>runghc prog.hs input.txt</tt></p>
<pre name="code" class="brush:haskell;">

module Main where

import Data.String.Utils
import Data.List
import Data.Maybe
import Math.Combinat.Sets
import System.Environment
import Text.Printf

data OperationResult = OperationResult {
     oper              :: Int -&gt; [Int] -&gt; Bool
     , msg             :: String
}

availableOperations :: [OperationResult]
availableOperations =
                    [
                    OperationResult { oper = testMatchMul,
                                      msg = &quot;mul&quot; },
                    OperationResult { oper = testMatchDiv,
                                      msg = &quot;div&quot; },
                    OperationResult { oper = testMatchSum,
                                      msg = &quot;add&quot; },
                    OperationResult { oper = testMatchSub,
                                      msg = &quot;sub&quot; }
                    ]

liftLine :: String -&gt; [Int]
liftLine l = sort $ fmap ( read . strip ) $ split &quot;,&quot; l

matchMessage :: String -&gt; [Int] -&gt; Int -&gt; String
matchMessage s xs n = printf &quot;%s does %s with %s&quot;
                      s ( show n ) ( show xs )

testMatchMul :: Int -&gt; [Int] -&gt; Bool
testMatchMul n xs = n == foldr (*) 1 xs

testMatchDiv :: Int -&gt; [Int] -&gt; Bool
testMatchDiv n xs = dm == n &amp;&amp; dr == 0
                    where (dm,dr) = divMod ( head xs ) ( last xs )

testMatchSum :: Int -&gt; [Int] -&gt; Bool
testMatchSum n xs = n == foldr (+) 0 xs

testMatchSub :: Int -&gt; [Int] -&gt; Bool
testMatchSub n xs = n == foldr (-) 0 xs

applyOperation :: [Int] -&gt; Int -&gt; OperationResult -&gt; Maybe String
applyOperation xs x y = if oper y x xs
                           then Just $ matchMessage ( msg y ) xs x
                           else Nothing

matchOperation :: [OperationResult] -&gt; [Int] -&gt; Int -&gt; [Maybe String]
matchOperation ops xs x = fmap (applyOperation xs x) ops

findMatch :: [Int] -&gt; [Int] -&gt; [String]
findMatch rs xs = fmap fromJust
                  $ filter ( /= Nothing )
                  $ join []
                  $ fmap (matchOperation availableOperations rs) xs

createCombinations :: [[Int]] -&gt; [[Int]]
createCombinations xs = join [] $ fmap (choose 2) xs

procResults :: [String] -&gt; IO ()
procResults = foldr ((&gt;&gt;) . putStrLn) (putStrLn &quot;End!&quot;)

main :: IO ()
main = do [i] &lt;- getArgs
          f &lt;- readFile i
          let rows = fmap liftLine $ lines f
              comb = createCombinations rows
              oset = join [] $ nub $ join []
                     $ fmap ( x -&gt; fmap (findMatch x) rows ) comb
              in procResults oset
                 &gt;&gt; print comb
</pre>
<p>Where having a sample input file with three numbers per line as follows:</p>
<pre name="code" class="brush:bash;">
4, 2, 8
6, 2, 12
6, 2, 3
9, 12, 108
4, 16, 64
</pre>
<p>Should be processed as follows:</p>
<pre name="code" class="brush:bash;">

08:21 [dmw@www:1 exercises]$ ghc --make challenge20120212.hs -o challenge20120212
[1 of 1] Compiling Main             ( challenge20120212.hs, challenge20120212.o )
Linking challenge20120212 ...
08:21 [dmw@www:1 exercises]$ ./challenge20120212 ./challenge20120212.txt
mul does 8 with [2,4]
add does 6 with [2,4]
mul does 16 with [2,8]
add does 12 with [4,8]
add does 8 with [2,6]
mul does 12 with [2,6]
mul does 6 with [2,3]
add does 9 with [3,6]
mul does 108 with [9,12]
mul does 64 with [4,16]
End!
[[2,4],[2,8],[4,8],[2,6],[2,12],[6,12],[2,3],[2,6],[3,6],[9,12],[9,108],[12,108],[4,16],[4,64],[16,64]]
</pre>
<p>Also, this program can process files with lines containing up to 4 numbers, no matter how many of them are present on the file, it will try all combinations thanks to the <tt>Math.Combinat.Sets</tt> module which is used to create the proper permutations with each line which are converted to Int lists with the <tt>liftLine</tt> function. Probably this is a kind of very basic MapReduce and non distributed implementation where you have various sets of unique permutations &mdash; or antisymmetric power of each list &mdash; and operations to check whether are executed.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/02/combinatorics-problem-in-haskell/">Permalink</a> |
<a href="http://coder.cl/2012/02/combinatorics-problem-in-haskell/#comments">6 comments</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/02/combinatorics-problem-in-haskell/&title=combinatorics problem in haskell">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/02/combinatorics-problem-in-haskell/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for ( 2e96b290f6c5ccd2bc6830557c0aba6e coder.cl/category/programming/haskell/feed/ ) in 0.47973 seconds, on May 18th, 2012 at 12:04 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on May 25th, 2012 at 12:04 pm UTC -->
