<?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>Sat, 04 Feb 2012 12:07:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>understanding mapreduce</title>
		<link>http://coder.cl/2012/02/understanding-mapreduce/</link>
		<comments>http://coder.cl/2012/02/understanding-mapreduce/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 12:07:01 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</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=2210</guid>
		<description><![CDATA[MapReduce is a distributed computing model introduced by Google with its framework for distributed computing called MapReduce. Its conceptual basis comes from a functional programming approach based mainly on the basic mathematical concept of Monoid treatment in functional programming. Basically a Monoid lifts data using map and process that data using fold &#8212; which is [...]]]></description>
			<content:encoded><![CDATA[<p><a href='http://en.wikipedia.org/wiki/MapReduce' title='MapReduce' rel="nofollow">MapReduce</a> is a distributed computing model introduced by Google with its framework for distributed computing called MapReduce. Its conceptual basis comes from a functional programming approach based mainly on the basic mathematical concept of Monoid treatment in functional programming. Basically a Monoid <i>lifts</i> data using <a href='http://en.wikipedia.org/wiki/Map_(higher-order_function)' title='Map (higher-order function)' rel="nofollow">map</a> and process that data using <a href='' title='http://en.wikipedia.org/wiki/Fold_(higher-order_function)' title='Fold (higher-order function)' rel="nofollow">fold</a> &mdash; which is called <i>reduce</i> in Python, returning the same bound type as its input &mdash; and can be expressed as the triple <img src='http://s.wordpress.com/latex.php?latex=%5Clangle%20A%2C%20%5Cvarepsilon%2C%20%5Ccdot%20%5Crangle&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\langle A, \varepsilon, \cdot \rangle' title='\langle A, \varepsilon, \cdot \rangle' class='latex' /> as the set <img src='http://s.wordpress.com/latex.php?latex=A&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='A' title='A' class='latex' />, the neutral element <img src='http://s.wordpress.com/latex.php?latex=%5Cvarepsilon&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\varepsilon' title='\varepsilon' class='latex' /> and the operation <img src='http://s.wordpress.com/latex.php?latex=%5Ccdot&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\cdot' title='\cdot' class='latex' />. The problem with the Monoid definition is the fact that it is bound to a type, where MapReduce is not bound to any type, and even it is not bound to a Category.</p>
<p><span id="more-2210"></span></p>
<p>The data is <i>lifted</i> from its original type when it is stored as set. We can have a basic and plain example on how operates the <tt>map</tt> over the data lifting its original type. For example we have a plain text file with lines containing numbers separated by spaces and we want to extract the product for each line of those numbers. Since the data is plain text and it is not a numeric type, we need to <i>lift</i> those numbers and convert them to type that we can operate &mdash; like Integer types. So, <tt>map</tt> implies data extraction and data conversion, to operate that data with <tt>reduce</tt>. Following our plain text file example, we have a plain text file as follows.</p>
<pre name="code" class="brush:bash;">

4 3 1 4 5
2 1 3 2 4
3 4 4 2 1
2 1 3 4 1
</pre>
<p>Now, we can use <tt>map</tt> to make the proper data conversion to <i>lift</i> the input data from the plain text file and process each line obtaining lists of integers instead of string characters as follows.</p>
<pre name="code" class="brush:haskell;">

module Main where

import System.Environment
import Data.String.Utils

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

main :: IO()
main = do [i] &lt;- getArgs
          f &lt;- readFile i
          let rows = fmap liftLine $ lines f
              in putStrLn $ show rows
</pre>
<p>In Haskell there are various <tt>map</tt> functions, here we using the most basic map function called <a href='http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Control-Monad.html#v%3Afmap' title='Control.Monad -&#038;gt fmap' rel="nofollow">fmap</a>, which is implemented using Functor type class with instance types or anonymous types. So, the <tt>liftLine</tt> function extract a list of Integers from each line splitting the line using the space character, then applies strip to each tokenized string and reads its input converting it to Integer, and since it is using <tt>fmap</tt>, it will return a List of Integers. Where map is used again to lift each line, so, we are using fmap Functor as our lifting map function to extract the data as Integer from its plain text representation.</p>
<p>Now we need to process that <i>lifted</i> data using map, to obtain our required product for each integer list. So, we need to use the <tt>reduce</tt> function, which has two variants in Haskell, foldl and foldr, and for our convenience, we will use foldr, where reduce has a Monoidal behaviour due to its typed nature and can be expressed as <img src='http://s.wordpress.com/latex.php?latex=%5Clangle%20A%2C%201%2C%20%5Ctimes%20%5Crangle&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\langle A, 1, \times \rangle' title='\langle A, 1, \times \rangle' class='latex' />.</p>
<pre name="code" class="brush:haskell;">

module Main where

import System.Environment
import Data.String.Utils

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

reduceProduct :: [Int] -&gt; Int
reduceProduct l = foldr (\ x y -&gt; x * y ) 1 l

main :: IO()
main = do [i] &lt;- getArgs
          f &lt;- readFile i
          let rows = fmap liftLine $ lines f
              prds = fmap reduceProduct rows
              in putStrLn $ show prds
</pre>
<p>So, those are the very basic principles of MapReduce, which is used to calculate the <a href='http://en.wikipedia.org/wiki/PageRank' title='PageRank' rel="nofollow">PageRank</a> on Google and get the site ranking on search results. So, this example is not distributed and it is a plain example of how it operates, just think on a distributed <tt>map</tt> and a distributed <tt>reduce</tt> operating with a very large amount of data to be processed. And there are various frameworks to work with MapReduce as model, because the original Google framework is not open source and you cannot work with it. As example of available frameworks supporting MapReduce as model you have <a href='http://hadoop.apache.org/' title='Apache Hadoop' rel="nofollow">Hadoop</a>, <a href='http://aws.amazon.com/elasticmapreduce/' title='Amazon Elastic MapReduce' rel="nofollow">Elastic MapReduce</a> and <a href='http://hackage.haskell.org/package/Holumbus-MapReduce' title='The Holumbus-MapReduce package'>Holumbus</a>, so you can use this model with those frameworks reducing computation costs if you do not want to process your data with linear computations.</p>
<br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2012 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="http://coder.cl.qfl.wpcdn.arcostream.com/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2012. | <a href="http://coder.cl/2012/02/understanding-mapreduce/">Permalink</a> | <a href="http://coder.cl/2012/02/understanding-mapreduce/#comments">No comment</a><br/>Post tags: <br/></small></p>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6234432850133541";
/* main-feed */
google_ad_slot = "0763600725";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/02/understanding-mapreduce/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>programming practice 1991-c, part 2</title>
		<link>http://coder.cl/2012/01/programming-practice-1991-c-part-2/</link>
		<comments>http://coder.cl/2012/01/programming-practice-1991-c-part-2/#comments</comments>
		<pubDate>Sun, 01 Jan 2012 19:16:32 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</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=2140</guid>
		<description><![CDATA[As you know I am learning Haskell and doing small exercises based on the ACM ICPC problem archive. I am using those problem sets as my Haskell practice. The task presented on the problem 1991-c is related to a small DSL which handles concurrency simulations, using two simple instruction called lock and unlock to switch [...]]]></description>
			<content:encoded><![CDATA[<p>As you know I am learning Haskell and doing small exercises based on the ACM ICPC problem archive. I am using those problem sets as my Haskell practice. The task presented on the problem <a href='http://www.ntnu.edu.tw/acm/ProblemSetArchive/A_FINALS/1991/prob_c.html' title='Problem C, Concurrency Simulator'>1991-c</a> is related to a small DSL which handles concurrency simulations, using two simple instruction called <tt>lock</tt> and <tt>unlock</tt> to switch between <i>running</i> and <i>ready</i> states. The DSL defined for this problem seems to be simple. I have used the Parsec Haskell package to build the language parser. Where on my <a href='http://coder.cl/2011/12/programming-practice-199-c-part-1/' title='programming practice 1991-c, part 1'>last post about this problem</a> I have created the program parser, and now I build the interpreter.</p>
<p><span id="more-2140"></span></p>
<p>So, the language syntax was formalized using an EBNF grammar specification, we can understand it as follows.</p>
<pre name="code" class="brush:haskell;">

&lt;eol&gt;            ::= "\n" | "\r" | "\r\n"
&lt;white-space&gt;    ::= " " | "\t"
&lt;assign-sign&gt;    ::= "="
&lt;variable&gt;       ::= ["a"-"z"]
&lt;number&gt;         ::= ["0"-"9"]+
&lt;print-literal&gt;  ::= "print"
&lt;lock-literal&gt;   ::= "lock"
&lt;unlock-literal&gt; ::= "unlock"
&lt;end-literal&gt;    ::= "end"
&lt;assign-var&gt;     ::= &lt;variable&gt; ( &lt;white-space&gt; )+ &lt;assign-sign&gt; ( &lt;white-space&gt; )+ &lt;number&gt; &lt;eol&gt;
&lt;print-var&gt;      ::= &lt;print-literal&gt; ( &lt;white-space&gt; )+ &lt;variable&gt; &lt;eol&gt;
&lt;lock-inst&gt;      ::= &lt;lock-literal&gt; &lt;eol&gt;
&lt;unlock-inst&gt;    ::= &lt;unlock-literal&gt; &lt;eol&gt;
&lt;quantum-seqs&gt;   ::= ( &lt;number&gt; ( &lt;white-space&gt; | &lt;eol&gt; ) )+
&lt;program&gt;        ::= ( &lt;assign-var&gt;
                     | &lt;print-var&gt;
                     | &lt;lock-inst&gt;
                     | &lt;unlock-inst&gt; )+
                     &lt;end&gt;
&lt;program-files&gt;  ::= &lt;quantum-seqs&gt; ( &lt;program&gt; )+
</pre>
<p>And it runs a parallel and concurrent context, using locks with <tt>lock</tt> and <tt>unlock</tt> primitives to gain exclusive execution of each <i>program</i>. So, I have used Haskell ADT to hold the instruction modifying the <tt>PInstruction</tt> structure as follows.</p>
<pre name="code" class="brush:haskell">

data PInstructionType = IsPLock
                        | IsPAssign
                        | IsPPrint
                        | IsPEnd
                          deriving (Show, Eq)

data PInstruct = PVAssign PVariableAssign
                 | PPLock PProgramLock
                 | PVPrint PPrintVar
                 | PEP PEndP
                   deriving (Show, Eq)

data PInstruction = PInstruction {
  inst           :: PInstruct
  , itype        :: PInstructionType
  , vend         :: Bool
  } deriving (Eq)
</pre>
<p>The instruction element becomes a Haskell ADT holding a particular instruction which holds which data should be processed using a single function that runs each step of the DSL program using output and a program context which is changed according each instruction. For that task and to differentiate between output and context related instruction, like variable assignment and locking instructions, I have used an Either construct, which allows me to return even a Haskell string to be printed on the screen or the modified program context itself.</p>
<pre name="code" class="brush:haskell;">

data PProgramSet = PProgramSet {
  vars         :: Map.Map Char Int
  , lock       :: Bool
  , ilock      :: Int
  , idx        :: Int
  , pidx       :: Int
  , progs      :: [ PProgram ]
  }

runInstruction :: PProgramSet -> PInstruction -> Either String PProgramSet
runInstruction s i | itype i == IsPAssign = Right
                                            $ runAssign s
                                            $ uwAssignIns ( inst i )
                   | itype i == IsPPrint  = Left
                                            $ runPrint s
                                            $ uwPrintIns ( inst i )
                   | itype i == IsPEnd    = Left ".!"
                   | itype i == IsPLock   = Right
                                            $ runLock s
                                            $ uwLockIns ( inst i )
                   | otherwise = Left ".!"
</pre>
<p>Where the program context is held on a <tt>PProgramSet</tt> instance, using a Haskell <tt>Data.Map</tt> instance that holds the variable name as char and its value as integer, where the instruction ADT is unwrapped using the <i>uw</i> set of function, and each specific statement is handled using guards which are verifying the instruction type <tt>itype</tt>.</p>
<p>So, the instruction collection is processed using a recursive function which handle end statements and stores them in a <tt>PProgramSet</tt>, returning the collection, that collection is passed to the instruction runner which handles each instruction step as a context modifier or an output statement.</p>
<pre name="code" class="brush:haskell;">

buildProgram :: PProgram
                -&gt; [ PInstruction ] -&gt; [ PInstruction ]
                -&gt; [ PProgram ] -&gt; [ PProgram ]
buildProgram n [] [] [] = buildProgram n (tasks n) [] []
buildProgram n [] [] ns = ns
buildProgram n [] ms ns = ns
buildProgram n (x:xs) ms ns = if itype x == IsPEnd
                                 then let pp = createPProgram (taskSet n) ms
                                          nns = (ns ++ [pp])
                                          in buildProgram n xs ms nns
                                 else let nms = (ms ++ [x])
                                          in buildProgram n xs nms ns

runPrograms :: PProgramSet -&gt; IO ()
runPrograms s = if checkFinished s
                   then putStrLn ".!"
                   else let is = runStep s
                            ri = runInstruction s is
                            in case ri of
                                    Left  st -&gt; putStrLn st
                                                &gt;&gt; runPrograms ( calculateIndex s )
                                    Right xs -&gt; runPrograms ( calculateIndex xs )

main :: IO ()
main = do [f] &lt;- getArgs
          c &lt;- readFile f
          let prg = fromJust $ extractProgram $ parseProgram c
              grp = buildProgramSet $ buildProgram prg [] [] []
              in runPrograms grp
</pre>
<p>I have removed the <tt>IORef</tt> statements and replaced them by a context driven interpreter, just to make it fully functional instead of using state driven features of Haskell. So, the interpreter remains fully functional and I do not have used any state-full features, like StateMonad, IORef or MVar.</p>
<br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2012 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="http://coder.cl.qfl.wpcdn.arcostream.com/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2012. | <a href="http://coder.cl/2012/01/programming-practice-1991-c-part-2/">Permalink</a> | <a href="http://coder.cl/2012/01/programming-practice-1991-c-part-2/#comments">No comment</a><br/>Post tags: <br/></small></p>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6234432850133541";
/* main-feed */
google_ad_slot = "0763600725";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/01/programming-practice-1991-c-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jquery is not a monad</title>
		<link>http://coder.cl/2011/12/jquery-is-not-a-monad/</link>
		<comments>http://coder.cl/2011/12/jquery-is-not-a-monad/#comments</comments>
		<pubDate>Mon, 19 Dec 2011 12:43:45 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</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=2118</guid>
		<description><![CDATA[There are some nice articles explaining that jQuery is a Monad, from the basis that jQuery chains computations with a returning type &#8212; with very simple words &#8212; but that is not enough to say that jQuery is a Monad. A Monad should meet certain conditions, from supplying support to its laws to defining the [...]]]></description>
			<content:encoded><![CDATA[<p>There are some nice articles explaining that jQuery is a Monad, from the basis that jQuery chains computations with a returning type &mdash; with very simple words &mdash; but that is not enough to say that jQuery is a Monad. A Monad should meet certain conditions, from supplying support to its laws to defining the proper methods covering its monadic behaviour. So, it basically should supply support for the three Monad Laws, called <i>associativity</i>, <i>right identity</i> and <i>left identity</i>, where all of them are applied to the same type &mdash; or category from its Math background.</p>
<p><span id="more-2118"></span></p>
<pre name="code" class="brush:haskell;">

class Monad m where
      (&gt;&gt;=) :: m a -&gt; (a -&gt; m b) -&gt; m b
      (&gt;&gt;) :: m a -&gt; m b -&gt; m b
      return :: a -&gt; m a
      fail :: String -&gt; m a
</pre>
<p>We can start saying that a Monad is bound to a type, where chained computations relates to the same type on each link. And jQuery is called first with a varying type argument called <i>selector</i>, which can be either a DOM object itself or a string holding a jQuery selector, throwing a DOM object collection as internal result, but it returns the jQuery instance as resulting object always. So, jQuery handles different types, disallowing the category boundaries.</p>
<p>Analysing its properties, a Monad has an endofunctor <i>T : X &rarr; X</i> covering its category. Where we have seen that jQuery holds different categories on its computations, and since jQuery provides different categories on different methods, the natural transformation <i>&mu; : T &times; T &rarr; T</i> cannot be meet, and it is also being broken by methods like <a href='http://api.jquery.com/remove/' title='.remove()'><tt>remove()</tt></a> and <a href='http://api.jquery.com/detach/' title='.detach()'><tt>detach()</tt></a>. Also, the natural transformation <i>&eta; : I &rarr; T</i>, providing identity to Monad endofunctor is not supplied on any method of jQuery, where the jQuery instance is returned always as identity of itself, disallowing the category boundaries supplied by the selector and the monadic type covered by its definition.</p>
<p>So, with the cases above, we can say that the <i>associativity</i> law <i>&mu;(&mu;(T &times; T) &times; T)) = &mu;(T &times; &mu;(T &times; T))</i> cannot be meet once the <i>&mu;</i> transformation is broken. And the <i>left identity</i> and the <i>right identity</i> which are specified by <i>&mu;(&eta;(T)) = T = &mu;(T(&eta;))</i> are not provided by any method, since the jQuery instance returns itself always, instead of delivering the selector results. On certain cases, probably <i>right identity</i> is supplied on very specific cases, like the <a href='http://api.jquery.com/replaceWith/' title='.replaceWith()'><tt>replaceWith()</tt></a> method, which is similar to its definition <tt>(&gt;&gt;=) :: m a &rarr; (a &rarr; m b) &rarr; m b</tt> or the <tt>return :: a -&gt; m a</tt> operation, which binds both left and right identity without altering the results, no matter where it is placed.</p>
<p>With different types &mdash; or categories &mdash; you cannot cover a Monad, and with broken Monad laws and properties, you even cannot call Monad to jQuery. Also, the only one Monad operation supplied by jQuery is the <tt>&gt;&gt;=</tt> operator, where binds the <i>right identity</i> law, and once you call the <tt>&gt;&gt;</tt> operator related method the chain is broken, like calling <a href='http://api.jquery.com/each/' title='.each()'><tt>each()</tt></a>, <a href='http://api.jquery.com/remove/' title='.remove()'><tt>remove()</tt></a> and similar ones. So, expressing a chain in jQuery terms looking as follows.</p>
<pre name="code" class="brush:javascript;">
    $('#my_div').
       addClass('visible-block').
       removeClass('invisible-block').
       live('click', __click);
</pre>
<p>The code above represents a chain of computations, that can be expressed with a monadic form as follows.</p>
<pre name="code" class="brush:haskell;">

-- if jQuery is implemented in Haskell

    selectElement "#my_div"
        &gt;&gt;= addClass "visible-block"
        &gt;&gt;= removeClass "invisible-block"
        &gt;&gt;= liveEvent "click" __click
</pre>
<p>But what happens once you call the <a href='http://api.jquery.com/remove/' title='.remove()'><tt>remove()</tt></a> method using jQuery. Seems that the monadic operation is broken by calling them, and the most important event is the fact the it cannot recover its original <i>state</i> disallowing the computation chain and recovering its original behaviour, and the fact that a Monad do not have a state associated with it, once you declare it &mdash; like using the State Monad. So, calling methods like <a href='http://api.jquery.com/remove/' title='.remove()'><tt>remove()</tt></a> is similar to make use of the <tt>&gt;&gt;</tt> operation, but breaking the computation chain, without the proper recovery. At least a Monad can continue its operations, because it covers similar behaviours by design. In a simple example, once you delete a file using the <tt>IO</tt> Monad, you can continue reading files, once you remove a DOM object from its tree using jQuery, you cannot continue operating over the DOM tree, and you need to recall the jQuery instance, where a Monad should meet its laws, which can be <a href='http://www.haskell.org/tutorial/monads.html' title='About Monads'>expressed as follows</a>.</p>
<pre name="code" class="brush: haskell;">

return a &gt;&gt;= k = k a
m &gt;&gt;= return = m
xs &gt;&gt;= return . f = fmap f xs
m &gt;&gt;= (\x -&gt; k x &gt;&gt;= h) = (m &gt;&gt;= k) &gt;&gt;= h
</pre>
<p>So, the laws above are not supplied by jQuery on all its operations, because the computation chain is broken in certain cases, disallowing a continous operation. For example with <a href='http://api.jquery.com/remove/' title='.remove()'><tt>remove()</tt></a> you cannot implement <tt>return a &gt;&gt;= k = k a</tt>, and using remove it&#8217;s like using <tt>return a &gt;&gt; k b</tt>, breaking the chain and altering the functor results, despite the jQuery instance is returned always &mdash; as the proper Monad implementation requires &mdash; the selection remains empty after using <tt>remove()</tt> disallowing the further normal operations.</p>
<br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2011 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="http://coder.cl.qfl.wpcdn.arcostream.com/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2011. | <a href="http://coder.cl/2011/12/jquery-is-not-a-monad/">Permalink</a> | <a href="http://coder.cl/2011/12/jquery-is-not-a-monad/#comments">No comment</a><br/>Post tags: <br/></small></p>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6234432850133541";
/* main-feed */
google_ad_slot = "0763600725";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/12/jquery-is-not-a-monad/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>programming practice 1991-c, part 1</title>
		<link>http://coder.cl/2011/12/programming-practice-199-c-part-1/</link>
		<comments>http://coder.cl/2011/12/programming-practice-199-c-part-1/#comments</comments>
		<pubDate>Sat, 03 Dec 2011 14:25:09 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</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=2054</guid>
		<description><![CDATA[As you know I am learning Haskell and doing small exercises based on the ACM ICPC problem archive. I am using those problem sets as my Haskell practice. The task presented on the problem 1999-c is related to a small DSL which handles concurrency simulations, using two simple instruction called lock and unlock to switch [...]]]></description>
			<content:encoded><![CDATA[<p>As you know I am learning Haskell and doing small exercises based on the ACM ICPC problem archive. I am using those problem sets as my Haskell practice. The task presented on the problem <a href='http://www.ntnu.edu.tw/acm/ProblemSetArchive/A_FINALS/1991/prob_c.html' title='Problem C, Concurrency Simulator'>1999-c</a> is related to a small DSL which handles concurrency simulations, using two simple instruction called <tt>lock</tt> and <tt>unlock</tt> to switch between <i>running</i> and <i>ready</i> states. The DSL defined for this problem seems to be simple. I have used the Parsec Haskell package to build the language parser.</p>
<p><span id="more-2054"></span></p>
<table align="center" border="0">
<tr>
<th>Statement Type</th>
<th>Syntax</th>
</tr>
<tr>
<td>Assignment</td>
<td>variable = constant</td>
</tr>
<tr>
<td>Output</td>
<td>print variable</td>
</tr>
<tr>
<td>Begin Mutual Exclusion</td>
<td>lock</td>
</tr>
<tr>
<td>End Mutual Exclusion</td>
<td>unlock</td>
</tr>
<tr>
<td>Stop Execution</td>
<td>end</td>
</tr>
</table>
<p>The tokens are clearly defined and the <a href='http://hackage.haskell.org/packages/archive/parsec/3.0.0/doc/html/Text-Parsec-Token.html' title='Text.Parsec.Token Module'>Text.Parsec.Token module</a> would be used, but instead I have defined the parser using the Parsec monadic primitives reading them as it would be implemented using BNF grammar parser, creating a simple data structure to hold the program instructions.</p>
<pre name="code" class="brush: haskell;">

data PProgramLock = PLock
                  | PUnlock
                    deriving (Show, Eq)

data PVariableAssign = PVariableAssign {
  varName       :: Char
  , varValue    :: Int
  } deriving (Show, Eq)

data PPrintVar = PPrintVar {
  varn          :: Char
  } deriving (Show, Eq)

data PInstructionSet = PInstructionSet [ Int ]
                     deriving (Show, Eq)

data PInstructionType = IsPLock
                      | IsPAssign
                      | IsPPrint
                      | IsPEnd
                        deriving (Show, Eq)

data PInstruction = PInstruction {
  vassign        :: Maybe PVariableAssign
  , vlock        :: Maybe PProgramLock
  , vprint       :: Maybe PPrintVar
  , itype        :: PInstructionType
  , vend         :: Bool
  } deriving (Show, Eq)

data PProgram = PProgram {
  taskSet       :: PInstructionSet
  , tasks       :: [ PInstruction ]
  } deriving (Show, Eq)
</pre>
<p>Once I have defined the structure to hold the program, I have created the parser using the Monadic primitives from the Parsec package and its modules, mainly the <tt>GenParser</tt> Monad, allowing me to tokenize the program and store its structure in the data structures defined above. The core parser is defined as follows.</p>
<pre name="code" class="brush: haskell;">

parseInstruction :: GenParser Char st PInstruction
parseInstruction = parseLock
                   &lt;|&gt; parseUnlock
                   &lt;|&gt; parseEnd
                   &lt;|&gt; parsePrint
                   &lt;|&gt; parseAssign

readInstructions :: GenParser Char st [PInstruction]
readInstructions = do instr &lt;- many parseInstruction
                      return ( instr )

parseTasks :: GenParser Char st [PInstruction]
parseTasks = do instr &lt;- readInstructions
                return instr

programParser :: GenParser Char st PProgram
programParser = do pTaskSet &lt;- parseTaskSet
                   pTasks &lt;- parseTasks
                   return PProgram {
                     taskSet = pTaskSet
                     , tasks = pTasks
                     }

parseProgram :: String -&gt; Either ParseError PProgram
parseProgram inp = parse programParser "[Invalid]" inp

main :: IO()
main = do [f] &lt;- getArgs
          c &lt;- readFile f
          let prg = parseProgram c
              in putStrLn $ show prg
</pre>
<p>Each instruction line is handled by the <tt>parseInstruction</tt> monadic function, where it tries all different parsers, using literals first, and then more complex constructions, like the variable assignment and variable printing instructions. Those expressions are handled by simple combinatorial token parsers defined as follows.</p>
<pre name="code" class="brush: haskell;">

parseLock :: GenParser Char st PInstruction
parseLock = do n &lt;- string lockInstLiteral
               e &lt;- readEol
               return $ createLockP PLock

parseUnlock :: GenParser Char st PInstruction
parseUnlock = do n &lt;- string unlockInstLiteral
                 e &lt;- readEol
                 return $ createLockP PUnlock

parseAssign :: GenParser Char st PInstruction
parseAssign = do dvar &lt;- parseVar
                 dassign &lt;- parseAssignment
                 dint &lt;- parseInteger
                 deol &lt;- readEol
                 return $ createAssignVarP dvar dint

parsePrint :: GenParser Char st PInstruction
parsePrint = do dprint &lt;- string printLiteral
                dspace &lt;- many $ char ' '
                dvar &lt;- oneOf validLetterChars
                deol &lt;- readEol
                return $ createPrintP dvar
</pre>
<p>So, if you follow the language, it is quite simple, probably it can be defined as follows.</p>
<pre name="code" class="brush:bash;">

&lt;eol&gt;            ::= "\n" | "\r" | "\r\n"
&lt;white-space&gt;    ::= " " | "\t"
&lt;assign-sign&gt;    ::= "="
&lt;variable&gt;       ::= ["a"-"z"]
&lt;number&gt;         ::= ["0"-"9"]+
&lt;print-literal&gt;  ::= "print"
&lt;lock-literal&gt;   ::= "lock"
&lt;unlock-literal&gt; ::= "unlock"
&lt;end-literal&gt;    ::= "end"
&lt;assign-var&gt;     ::= &lt;variable&gt; ( &lt;white-space&gt; )+ &lt;assign-sign&gt; ( &lt;white-space&gt; )+ &lt;number&gt; &lt;eol&gt;
&lt;print-var&gt;      ::= &lt;print-literal&gt; ( &lt;white-space&gt; )+ &lt;variable&gt; &lt;eol&gt;
&lt;lock-inst&gt;      ::= &lt;lock-literal&gt; &lt;eol&gt;
&lt;unlock-inst&gt;    ::= &lt;unlock-literal&gt; &lt;eol&gt;
&lt;quantum-seqs&gt;   ::= ( &lt;number&gt; ( &lt;white-space&gt; | &lt;eol&gt; ) )+
&lt;program&gt;        ::= ( &lt;assign-var&gt;
                     | &lt;print-var&gt;
                     | &lt;lock-inst&gt;
                     | &lt;unlock-inst&gt; )+
                     &lt;end&gt;
&lt;program-files&gt;  ::= &lt;quantum-seqs&gt; ( &lt;program&gt; )+
</pre>
<p>Which is the same implementation that I have provided to Haskell using the Parsec GenParser Monad.</p>
<br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2011 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="http://coder.cl.qfl.wpcdn.arcostream.com/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2011. | <a href="http://coder.cl/2011/12/programming-practice-199-c-part-1/">Permalink</a> | <a href="http://coder.cl/2011/12/programming-practice-199-c-part-1/#comments">5 comments</a><br/>Post tags: <br/></small></p>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6234432850133541";
/* main-feed */
google_ad_slot = "0763600725";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/12/programming-practice-199-c-part-1/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>impressions on hlint</title>
		<link>http://coder.cl/2011/11/impressions-on-hlint/</link>
		<comments>http://coder.cl/2011/11/impressions-on-hlint/#comments</comments>
		<pubDate>Thu, 24 Nov 2011 11:13:14 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</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=2015</guid>
		<description><![CDATA[I have worked with various static analysis tools, but the first time that I have worked with hlint, the Haskell static checker, I was impressed because it has suggested me a &#951;-reduction. What is a &#951;-reduction?, in simple words it finds &#955; equivalences between expressions, reducing function call sequences to less functions. The most classic [...]]]></description>
			<content:encoded><![CDATA[<p>I have worked with various static analysis tools, but the first time that I have worked with <i>hlint</i>, the Haskell static checker, I was impressed because it has suggested me a &eta;-reduction. What is a &eta;-reduction?, in simple words it finds <i>&lambda;</i> equivalences between expressions, reducing function call sequences to less functions. The most classic reduction is the identity combinator reduction, where a function with the form <i>(&lambda;xyz.(x)yz)(&lambda;rs.t)mn</i> can be reduced just to the function application <i>t</i>.</p>
<p><span id="more-2015"></span></p>
<p>A source code example for this very basic reduction can be implemented in Haskell with the following code.</p>
<pre class="brush: haskell;">

module Main where

addInt :: Int -> Int -> Int
addInt a b = a + b

fwrap :: (Int -> Int -> Int) -> Int -> Int -> Int
fwrap f a b = f a b

fwrapX :: (Int -> Int -> Int) -> Int -> Int -> Int
fwrapX f = f

main :: IO()
main = do print $ fwrap addInt 5 6
           print $ fwrapX addInt 5 6
</pre>
<p>Where <tt>fwrap</tt> and <tt>fwrapX</tt> are &lambda; equivalent. The <tt>fwrap</tt> function has the form <i>(&lambda;xyz.(x)yz)(&lambda;rs.t)mn</i> and <tt>fwrapX</tt> has the form of the function application <i>t</i>. So, hlint in this case makes the proper suggestion about the obvious &eta;-reduction as follows. I am using untyped lambda calculus expressions just to simplify the expressions, so you cannot get confused.</p>
<pre class="brush: bash;">
hlint.hs:9:1: Error: Eta reduce
Found:
  fwrap f a b = f a b
Why not:
  fwrap f = f

1 suggestion
</pre>
<p>Is very nice to work with a language capable of doing that kind of suggestions with its static analyzer. So, hlint is almost evaluating expressions in a manner that I have never seen in other static analyzers, making your code &mdash; probably &mdash; cleaner than others static analyzers. I hope that other static analyzers will include formal reduction suggestions in the future, so can have cleaner code and probably less redundant. Would be nice to have a similar static analyzer in Python, C, C++ and Java, I hope that some developer will include that kind checks in some of those languages. On C we have splint, which works great, but it doesn&#8217;t have support for formal reductions. At the other side, in Python we have pep8, pylint, pycheckers and pyflakes, but they doesn&#8217;t support formal reductions too. I think that certain imperative expression allows you to be analyze the code as functional code, so there should not be any problem applying this kind of theory.</p>
<p>There are many theoretical approaches that can be used while you are programming, you just need the proper knowledge to handle that theoretical background. Having only the object oriented approach will not make you a better programmer.</p>
<br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2011 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="http://coder.cl.qfl.wpcdn.arcostream.com/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2011. | <a href="http://coder.cl/2011/11/impressions-on-hlint/">Permalink</a> | <a href="http://coder.cl/2011/11/impressions-on-hlint/#comments">No comment</a><br/>Post tags: <br/></small></p>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6234432850133541";
/* main-feed */
google_ad_slot = "0763600725";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/11/impressions-on-hlint/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  coder.cl/category/programming/haskell/feed/ ) in 0.38686 seconds, on Feb 7th, 2012 at 3:16 am UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on Feb 7th, 2012 at 4:16 am UTC -->
