her.esy.fun/src/Scratch/en/blog/Haskell-the-Hard-Way/index.html

2389 lines
227 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>YBlog - Learn Haskell Fast and Hard</title>
<meta name="keywords" content="Haskell, programming, functional, tutorial" />
<link rel="shortcut icon" type="image/x-icon" href="../../../../Scratch/img/favicon.ico" />
<link rel="stylesheet" type="text/css" href="/css/y.css" />
<link rel="stylesheet" type="text/css" href="/css/legacy.css" />
<link rel="alternate" type="application/rss+xml" title="RSS" href="/rss.xml" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="apple-touch-icon" href="../../../../Scratch/img/about/FlatAvatar@2x.png" />
<!--[if lt IE 9]>
<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE9.js"></script>
<![endif]-->
<!-- IndieAuth -->
<link href="https://twitter.com/yogsototh" rel="me">
<link href="https://github.com/yogsototh" rel="me">
<link href="mailto:yann.esposito@gmail.com" rel="me">
<link rel="pgpkey" href="../../../../pubkey.txt">
</head>
<body lang="en" class="article">
<div id="content">
<div id="header">
<div id="choix">
<span id="choixlang">
<a href="../../../../Scratch/fr/blog/Haskell-the-Hard-Way/">French</a>
</span>
<span class="tomenu"><a href="#navigation">↓ Menu ↓</a></span>
<span class="flush"></span>
</div>
</div>
<div id="titre">
<h1>Learn Haskell Fast and Hard</h1>
<h2>Blow your mind with Haskell</h2>
</div>
<div class="flush"></div>
<div id="afterheader" class="article">
<div class="corps">
<div>
<img src="../../../../Scratch/img/blog/Haskell-the-Hard-Way/magritte_pleasure_principle.jpg" alt="Magritte pleasure principle" />
</div>
<div class="intro">
<p><span class="sc"><abbr title="Too long; didn't read">tl;dr</abbr>: </span> A very short and dense tutorial for learning Haskell.</p>
<p>Thanks to:</p>
<ul>
<li><a href="https://plus.google.com/u/0/113751420744109290534">Oleg Taykalo</a> you can find a Russian translation here: <a href="http://habrahabr.ru/post/152889/">Part 1</a> <em>&amp;</em> <a href="http://habrahabr.ru/post/153383/">Part 2</a>,</li>
<li><a href="http://silly-bytes.blogspot.fr">Daniel Campoverde</a> for the Spanish translation here: <a href="http://silly-bytes.blogspot.fr/2016/06/aprende-haskell-rapido-y-dificil_29.html">Aprende Haskell rápido y difícil</a>,</li>
<li><a href="http://github.com/joom">Joomy Korkut</a> for the Turkish translation here: <a href="https://github.com/joom/zor-yoldan-haskell">Zor Yoldan Haskell</a>.</li>
</ul>
<blockquote>
<center>
<hr style="width:30%;float:left;border-color:#CCCCD0;margin-top:1em" />
<span class="sc"><b>Table of Content</b></span>
<hr style="width:30%;float:right;border-color:#CCCCD0;margin-top:1em" />
</center>
<div class="toc">
<ul>
<li><a href="#introduction">Introduction</a>
<ul>
<li><a href="#install">Install</a></li>
<li><a href="#don-t-be-afraid">Dont be afraid</a></li>
<li><a href="#very-basic-haskell">Very basic Haskell</a>
<ul>
<li><a href="#function-declaration">Function declaration</a></li>
<li><a href="#a-type-example">A Type Example</a></li>
</ul></li>
</ul></li>
<li><a href="#essential-haskell">Essential Haskell</a>
<ul>
<li><a href="#notations">Notations</a>
<ul>
<li><a href="#arithmetic">Arithmetic</a></li>
<li><a href="#logic">Logic</a></li>
<li><a href="#powers">Powers</a></li>
<li><a href="#lists">Lists</a></li>
<li><a href="#strings">Strings</a></li>
<li><a href="#tuples">Tuples</a></li>
<li><a href="#deal-with-parentheses">Deal with parentheses</a></li>
</ul></li>
<li><a href="#useful-notations-for-functions">Useful notations for functions</a></li>
</ul></li>
<li><a href="#hard-part">Hard Part</a>
<ul>
<li><a href="#functional-style">Functional style</a>
<ul>
<li><a href="#higher-order-functions">Higher Order Functions</a></li>
</ul></li>
<li><a href="#types">Types</a>
<ul>
<li><a href="#type-inference">Type inference</a></li>
<li><a href="#type-construction">Type construction</a></li>
<li><a href="#recursive-type">Recursive type</a></li>
<li><a href="#trees">Trees</a></li>
</ul></li>
<li><a href="#infinite-structures">Infinite Structures</a></li>
</ul></li>
<li><a href="#hell-difficulty-part">Hell Difficulty Part</a>
<ul>
<li><a href="#deal-with-io">Deal With IO</a></li>
<li><a href="#io-trick-explained">IO trick explained</a></li>
<li><a href="#monads">Monads</a>
<ul>
<li><a href="#maybe-monad">Maybe is a monad</a></li>
<li><a href="#the-list-monad">The list monad</a></li>
</ul></li>
</ul></li>
<li><a href="#appendix">Appendix</a>
<ul>
<li><a href="#more-on-infinite-tree">More on Infinite Tree</a></li>
</ul></li>
</ul>
</div>
</blockquote>
</div>
<div class="intro">
<p>I really believe all developers should learn Haskell. I dont think everyone needs to be super Haskell ninjas, but they should at least discover what Haskell has to offer. Learning Haskell opens your mind.</p>
<p>Mainstream languages share the same foundations:</p>
<ul>
<li>variables</li>
<li>loops</li>
<li>pointers<a href="#fn1" class="footnote-ref" id="fnref1"><sup>1</sup></a></li>
<li>data structures, objects and classes (for most)</li>
</ul>
<p>Haskell is very different. The language uses a lot of concepts I had never heard about before. Many of those concepts will help you become a better programmer.</p>
<p>But learning Haskell can be hard. It was for me. In this article I try to provide what I lacked during my learning.</p>
<p>This article will certainly be hard to follow. This is on purpose. There is no shortcut to learning Haskell. It is hard and challenging. But I believe this is a good thing. It is because it is hard that Haskell is interesting.</p>
<p>The conventional method to learning Haskell is to read two books. First <a href="http://learnyouahaskell.com">“Learn You a Haskell”</a> and just after <a href="http://www.realworldhaskell.org">“Real World Haskell”</a>. I also believe this is the right way to go. But to learn what Haskell is all about, youll have to read them in detail.</p>
<p>In contrast, this article is a very brief and dense overview of all major aspects of Haskell. I also added some information I lacked while I learned Haskell.</p>
<p>The article contains five parts:</p>
<ul>
<li>Introduction: a short example to show Haskell can be friendly.</li>
<li>Basic Haskell: Haskell syntax, and some essential notions.</li>
<li>Hard Difficulty Part:
<ul>
<li>Functional style; a progressive example, from imperative to functional style</li>
<li>Types; types and a standard binary tree example</li>
<li>Infinite Structure; manipulate an infinite binary tree!</li>
</ul></li>
<li>Hell Difficulty Part:
<ul>
<li>Deal with IO; A very minimal example</li>
<li>IO trick explained; the hidden detail I lacked to understand IO</li>
<li>Monads; incredible how we can generalize</li>
</ul></li>
<li>Appendix:
<ul>
<li>More on infinite tree; a more math oriented discussion about infinite trees</li>
</ul></li>
</ul>
<blockquote>
Note: Each time you see a separator with a filename ending in <code>.lhs</code> you can click the filename to get this file. If you save the file as <code>filename.lhs</code>, you can run it with
<pre>
runhaskell filename.lhs
</pre>
<p>Some might not work, but most will. You should see a link just below.</p>
</blockquote>
</div>
<hr />
<p><a href="code/01_basic/10_Introduction/00_hello_world.lhs" class="cut">01_basic/10_Introduction/<strong>00_hello_world.lhs</strong></a></p>
<h2 id="introduction">
Introduction
</h2>
<h3 id="install">
Install
</h3>
<div>
<img src="../../../../Scratch/img/blog/Haskell-the-Hard-Way/Haskell-logo.png" alt />
</div>
<p>There are different way to install Haskell, I would recommend to use <a href="https://haskellstack.org"><code>stack</code></a>.</p>
<p>There are other way to install Haskell on your system you could visit, you can learn more about it by visiting <a href="https://haskell.org">haskell.org</a> or <a href="https://haskell-lang.org">haskell-lang.org</a></p>
<p>Tools:</p>
<ul>
<li><code>ghc</code>: Compiler similar to gcc for <code>C</code>.</li>
<li><code>ghci</code>: Interactive Haskell (REPL)</li>
<li><code>runhaskell</code>: Execute a program without compiling it. Convenient but very slow compared to compiled programs.</li>
</ul>
<h3 id="don-t-be-afraid">
Dont be afraid
</h3>
<div>
<img src="../../../../Scratch/img/blog/Haskell-the-Hard-Way/munch_TheScream.jpg" alt="The Scream" />
</div>
<p>Many books/articles about Haskell start by introducing some esoteric formula (quick sort, Fibonacci, etc…). I will do the exact opposite. At first I wont show you any Haskell super power. I will start with similarities between Haskell and other programming languages. Lets jump to the mandatory “Hello World”.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb1"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb1-1" title="1">main <span class="ot">=</span> <span class="fu">putStrLn</span> <span class="st">&quot;Hello World!&quot;</span></a></code></pre></div>
</div>
<p>To run it, you can save this code in a <code>hello.hs</code> and:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode zsh"><code class="sourceCode zsh"><a class="sourceLine" id="cb2-1" title="1">~ runhaskell ./hello.hs</a>
<a class="sourceLine" id="cb2-2" title="2">Hello World!</a></code></pre></div>
<p>or if you use <code>stack</code> first run <code>stack setup</code> and then:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode zsh"><code class="sourceCode zsh"><a class="sourceLine" id="cb3-1" title="1">~ stack runhaskell ./hello.hs</a>
<a class="sourceLine" id="cb3-2" title="2">Hello World!</a></code></pre></div>
<p>You could also download the literate Haskell source. You should see a link just above the introduction title. Download this file as <code>00_hello_world.lhs</code> and:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode zsh"><code class="sourceCode zsh"><a class="sourceLine" id="cb4-1" title="1">~ runhaskell 00_hello_world.lhs</a>
<a class="sourceLine" id="cb4-2" title="2">Hello World!</a></code></pre></div>
<p><a href="code/01_basic/10_Introduction/00_hello_world.lhs" class="cut">01_basic/10_Introduction/<strong>00_hello_world.lhs</strong> </a></p>
<hr />
<p><a href="code/01_basic/10_Introduction/10_hello_you.lhs" class="cut">01_basic/10_Introduction/<strong>10_hello_you.lhs</strong></a></p>
<p>Now, a program asking your name and replying “Hello” using the name you entered:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb5"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb5-1" title="1">main <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb5-2" title="2"> <span class="fu">print</span> <span class="st">&quot;What is your name?&quot;</span></a>
<a class="sourceLine" id="cb5-3" title="3"> name <span class="ot">&lt;-</span> <span class="fu">getLine</span></a>
<a class="sourceLine" id="cb5-4" title="4"> <span class="fu">print</span> (<span class="st">&quot;Hello &quot;</span> <span class="op">++</span> name <span class="op">++</span> <span class="st">&quot;!&quot;</span>)</a></code></pre></div>
</div>
<p>First, let us compare this with similar programs in a few imperative languages:</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode python"><code class="sourceCode python"><a class="sourceLine" id="cb6-1" title="1"><span class="co"># Python</span></a>
<a class="sourceLine" id="cb6-2" title="2"><span class="bu">print</span> <span class="st">&quot;What is your name?&quot;</span></a>
<a class="sourceLine" id="cb6-3" title="3">name <span class="op">=</span> <span class="bu">raw_input</span>()</a>
<a class="sourceLine" id="cb6-4" title="4"><span class="bu">print</span> <span class="st">&quot;Hello </span><span class="sc">%s</span><span class="st">!&quot;</span> <span class="op">%</span> name</a></code></pre></div>
<div class="sourceCode" id="cb7"><pre class="sourceCode ruby"><code class="sourceCode ruby"><a class="sourceLine" id="cb7-1" title="1"><span class="co"># Ruby</span></a>
<a class="sourceLine" id="cb7-2" title="2">puts <span class="st">&quot;What is your name?&quot;</span></a>
<a class="sourceLine" id="cb7-3" title="3">name = gets.chomp</a>
<a class="sourceLine" id="cb7-4" title="4">puts <span class="st">&quot;Hello </span><span class="ot">#{</span>name<span class="ot">}</span><span class="st">!&quot;</span></a></code></pre></div>
<div class="sourceCode" id="cb8"><pre class="sourceCode c"><code class="sourceCode c"><a class="sourceLine" id="cb8-1" title="1"><span class="co">// In C</span></a>
<a class="sourceLine" id="cb8-2" title="2"><span class="pp">#include </span><span class="im">&lt;stdio.h&gt;</span></a>
<a class="sourceLine" id="cb8-3" title="3"><span class="dt">int</span> main (<span class="dt">int</span> argc, <span class="dt">char</span> **argv) {</a>
<a class="sourceLine" id="cb8-4" title="4"> <span class="dt">char</span> name[<span class="dv">666</span>]; <span class="co">// &lt;- An Evil Number!</span></a>
<a class="sourceLine" id="cb8-5" title="5"> <span class="co">// What if my name is more than 665 character long?</span></a>
<a class="sourceLine" id="cb8-6" title="6"> printf(<span class="st">&quot;What is your name?</span><span class="sc">\n</span><span class="st">&quot;</span>);</a>
<a class="sourceLine" id="cb8-7" title="7"> scanf(<span class="st">&quot;%s&quot;</span>, name);</a>
<a class="sourceLine" id="cb8-8" title="8"> printf(<span class="st">&quot;Hello %s!</span><span class="sc">\n</span><span class="st">&quot;</span>, name);</a>
<a class="sourceLine" id="cb8-9" title="9"> <span class="cf">return</span> <span class="dv">0</span>;</a>
<a class="sourceLine" id="cb8-10" title="10">}</a></code></pre></div>
<p>The structure is the same, but there are some syntax differences. The main part of this tutorial will be dedicated to explaining why.</p>
<p>In Haskell there is a <code>main</code> function and every object has a type. The type of <code>main</code> is <code>IO ()</code>. This means <code>main</code> will cause side effects.</p>
<p>Just remember that Haskell can look a lot like mainstream imperative languages.</p>
<p><a href="code/01_basic/10_Introduction/10_hello_you.lhs" class="cut">01_basic/10_Introduction/<strong>10_hello_you.lhs</strong> </a></p>
<hr />
<p><a href="code/01_basic/10_Introduction/20_very_basic.lhs" class="cut">01_basic/10_Introduction/<strong>20_very_basic.lhs</strong></a></p>
<h3 id="very-basic-haskell">
Very basic Haskell
</h3>
<div>
<img src="../../../../Scratch/img/blog/Haskell-the-Hard-Way/picasso_owl.jpg" alt="Picasso minimal owl" />
</div>
<p>Before continuing you need to be warned about some essential properties of Haskell.</p>
<p><em>Functional</em></p>
<p>Haskell is a functional language. If you have an imperative language background, youll have to learn a lot of new things. Hopefully many of these new concepts will help you to program even in imperative languages.</p>
<p><em>Smart Static Typing</em></p>
<p>Instead of being in your way like in <code>C</code>, <code>C++</code> or <code>Java</code>, the type system is here to help you.</p>
<p><em>Purity</em></p>
<p>Generally your functions wont modify anything in the outside world. This means they cant modify the value of a variable, cant get user input, cant write on the screen, cant launch a missile. On the other hand, parallelism will be very easy to achieve. Haskell makes it clear where effects occur and where your code is pure. Also, it will be far easier to reason about your program. Most bugs will be prevented in the pure parts of your program.</p>
<p>Furthermore, pure functions follow a fundamental law in Haskell:</p>
<blockquote>
<p>Applying a function with the same parameters always returns the same value.</p>
</blockquote>
<p><em>Laziness</em></p>
<p>Laziness by default is a very uncommon language design. By default, Haskell evaluates something only when it is needed. In consequence, it provides a very elegant way to manipulate infinite structures, for example.</p>
<p>A last warning about how you should read Haskell code. For me, it is like reading scientific papers. Some parts are very clear, but when you see a formula, just focus and read slower. Also, while learning Haskell, it <em>really</em> doesnt matter much if you dont understand syntax details. If you meet a <code>&gt;&gt;=</code>, <code>&lt;$&gt;</code>, <code>&lt;-</code> or any other weird symbol, just ignore them and follows the flow of the code.</p>
<h4 id="function-declaration">
Function declaration
</h4>
<p>You might be used to declaring functions like this:</p>
<p>In <code>C</code>:</p>
<div class="sourceCode" id="cb9"><pre class="sourceCode c"><code class="sourceCode c"><a class="sourceLine" id="cb9-1" title="1"><span class="dt">int</span> f(<span class="dt">int</span> x, <span class="dt">int</span> y) {</a>
<a class="sourceLine" id="cb9-2" title="2"> <span class="cf">return</span> x*x + y*y;</a>
<a class="sourceLine" id="cb9-3" title="3">}</a></code></pre></div>
<p>In JavaScript:</p>
<div class="sourceCode" id="cb10"><pre class="sourceCode javascript"><code class="sourceCode javascript"><a class="sourceLine" id="cb10-1" title="1"><span class="kw">function</span> <span class="at">f</span>(x<span class="op">,</span>y) <span class="op">{</span></a>
<a class="sourceLine" id="cb10-2" title="2"> <span class="cf">return</span> x<span class="op">*</span>x <span class="op">+</span> y<span class="op">*</span>y<span class="op">;</span></a>
<a class="sourceLine" id="cb10-3" title="3"><span class="op">}</span></a></code></pre></div>
<p>in Python:</p>
<div class="sourceCode" id="cb11"><pre class="sourceCode python"><code class="sourceCode python"><a class="sourceLine" id="cb11-1" title="1"><span class="kw">def</span> f(x,y):</a>
<a class="sourceLine" id="cb11-2" title="2"> <span class="cf">return</span> x<span class="op">*</span>x <span class="op">+</span> y<span class="op">*</span>y</a></code></pre></div>
<p>in Ruby:</p>
<div class="sourceCode" id="cb12"><pre class="sourceCode ruby"><code class="sourceCode ruby"><a class="sourceLine" id="cb12-1" title="1"><span class="kw">def</span> f(x,y)</a>
<a class="sourceLine" id="cb12-2" title="2"> x*x + y*y</a>
<a class="sourceLine" id="cb12-3" title="3"><span class="kw">end</span></a></code></pre></div>
<p>In Scheme:</p>
<div class="sourceCode" id="cb13"><pre class="sourceCode scheme"><code class="sourceCode scheme"><a class="sourceLine" id="cb13-1" title="1">(<span class="ex">define</span><span class="fu"> </span>(f x y)</a>
<a class="sourceLine" id="cb13-2" title="2"> (<span class="op">+</span> (* x x) (* y y)))</a></code></pre></div>
<p>Finally, the Haskell way is:</p>
<div class="sourceCode" id="cb14"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb14-1" title="1">f x y <span class="ot">=</span> x<span class="op">*</span>x <span class="op">+</span> y<span class="op">*</span>y</a></code></pre></div>
<p>Very clean. No parenthesis, no <code>def</code>.</p>
<p>Dont forget, Haskell uses functions and types a lot. It is thus very easy to define them. The syntax was particularly well thought out for these objects.</p>
<h4 id="a-type-example">
A Type Example
</h4>
<p>Although it is not mandatory, type information for functions is usually made explicit. Its not mandatory because the compiler is smart enough to discover it for you. Its a good idea because it indicates intent and understanding.</p>
<p>Lets play a little. We declare the type using <code>::</code></p>
<div class="codehighlight">
<div class="sourceCode" id="cb15"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb15-1" title="1"><span class="ot"> f ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span></a>
<a class="sourceLine" id="cb15-2" title="2"> f x y <span class="ot">=</span> x<span class="op">*</span>x <span class="op">+</span> y<span class="op">*</span>y</a>
<a class="sourceLine" id="cb15-3" title="3"></a>
<a class="sourceLine" id="cb15-4" title="4"> main <span class="ot">=</span> <span class="fu">print</span> (f <span class="dv">2</span> <span class="dv">3</span>)</a></code></pre></div>
</div>
<pre><code>~ runhaskell 20_very_basic.lhs
13</code></pre>
<p><a href="code/01_basic/10_Introduction/20_very_basic.lhs" class="cut">01_basic/10_Introduction/<strong>20_very_basic.lhs</strong> </a></p>
<hr />
<p><a href="code/01_basic/10_Introduction/21_very_basic.lhs" class="cut">01_basic/10_Introduction/<strong>21_very_basic.lhs</strong></a></p>
<p>Now try</p>
<div class="codehighlight">
<div class="sourceCode" id="cb17"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb17-1" title="1"><span class="ot">f ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Int</span></a>
<a class="sourceLine" id="cb17-2" title="2">f x y <span class="ot">=</span> x<span class="op">*</span>x <span class="op">+</span> y<span class="op">*</span>y</a>
<a class="sourceLine" id="cb17-3" title="3"></a>
<a class="sourceLine" id="cb17-4" title="4">main <span class="ot">=</span> <span class="fu">print</span> (f <span class="fl">2.3</span> <span class="fl">4.2</span>)</a></code></pre></div>
</div>
<p>You should get this error:</p>
<pre><code>21_very_basic.lhs:6:23:
No instance for (Fractional Int)
arising from the literal `4.2'
Possible fix: add an instance declaration for (Fractional Int)
In the second argument of `f', namely `4.2'
In the first argument of `print', namely `(f 2.3 4.2)'
In the expression: print (f 2.3 4.2)</code></pre>
<p>The problem: <code>4.2</code> isnt an Int.</p>
<p><a href="code/01_basic/10_Introduction/21_very_basic.lhs" class="cut">01_basic/10_Introduction/<strong>21_very_basic.lhs</strong> </a></p>
<hr />
<p><a href="code/01_basic/10_Introduction/22_very_basic.lhs" class="cut">01_basic/10_Introduction/<strong>22_very_basic.lhs</strong></a></p>
<p>The solution: dont declare a type for <code>f</code> for the moment and let Haskell infer the most general type for us:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb19"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb19-1" title="1">f x y <span class="ot">=</span> x<span class="op">*</span>x <span class="op">+</span> y<span class="op">*</span>y</a>
<a class="sourceLine" id="cb19-2" title="2"></a>
<a class="sourceLine" id="cb19-3" title="3">main <span class="ot">=</span> <span class="fu">print</span> (f <span class="fl">2.3</span> <span class="fl">4.2</span>)</a></code></pre></div>
</div>
<p>It works! Luckily, we dont have to declare a new function for every single type. For example, in <code>C</code>, youll have to declare a function for <code>int</code>, for <code>float</code>, for <code>long</code>, for <code>double</code>, etc…</p>
<p>But, what type should we declare? To discover the type Haskell has found for us, just launch ghci:</p>
<pre><span class="low">
%</span> ghci<span class="low"><code>
GHCi, version 7.0.4: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package ffi-1.0 ... linking ... done.
Prelude></code></span> let f x y = x*x + y*y
<span class="low"><code>Prelude></code></span> :type f
<code>f :: Num a => a -> a -> a</code>
</pre>
<p>Uh? What is this strange type?</p>
<pre><code>Num a =&gt; a -&gt; a -&gt; a</code></pre>
<p>First, lets focus on the right part <code>a -&gt; a -&gt; a</code>. To understand it, just look at a list of progressive examples:</p>
<table>
<colgroup>
<col style="width: 27%" />
<col style="width: 72%" />
</colgroup>
<thead>
<tr class="header">
<th>The written type</th>
<th style="text-align: left;">Its meaning</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>Int</code></td>
<td style="text-align: left;">the type <code>Int</code></td>
</tr>
<tr class="even">
<td><code>Int -&gt; Int</code></td>
<td style="text-align: left;">the type function from <code>Int</code> to <code>Int</code></td>
</tr>
<tr class="odd">
<td><code>Float -&gt; Int</code></td>
<td style="text-align: left;">the type function from <code>Float</code> to <code>Int</code></td>
</tr>
<tr class="even">
<td><code>a -&gt; Int</code></td>
<td style="text-align: left;">the type function from any type to <code>Int</code></td>
</tr>
<tr class="odd">
<td><code>a -&gt; a</code></td>
<td style="text-align: left;">the type function from any type <code>a</code> to the same type <code>a</code></td>
</tr>
<tr class="even">
<td><code>a -&gt; a -&gt; a</code></td>
<td style="text-align: left;">the type function of two arguments of any type <code>a</code> to the same type <code>a</code></td>
</tr>
</tbody>
</table>
<p>In the type <code>a -&gt; a -&gt; a</code>, the letter <code>a</code> is a <em>type variable</em>. It means <code>f</code> is a function with two arguments and both arguments and the result have the same type. The type variable <code>a</code> could take many different type values. For example <code>Int</code>, <code>Integer</code>, <code>Float</code></p>
<p>So instead of having a forced type like in <code>C</code> and having to declare a function for <code>int</code>, <code>long</code>, <code>float</code>, <code>double</code>, etc., we declare only one function like in a dynamically typed language.</p>
<p>This is sometimes called parametric polymorphism. Its also called having your cake and eating it too.</p>
<p>Generally <code>a</code> can be any type, for example a <code>String</code> or an <code>Int</code>, but also more complex types, like <code>Trees</code>, other functions, etc. But here our type is prefixed with <code>Num a =&gt;</code>.</p>
<p><code>Num</code> is a <em>type class</em>. A type class can be understood as a set of types. <code>Num</code> contains only types which behave like numbers. More precisely, <code>Num</code> is class containing types which implement a specific list of functions, and in particular <code>(+)</code> and <code>(*)</code>.</p>
<p>Type classes are a very powerful language construct. We can do some incredibly powerful stuff with this. More on this later.</p>
<p>Finally, <code>Num a =&gt; a -&gt; a -&gt; a</code> means:</p>
<p>Let <code>a</code> be a type belonging to the <code>Num</code> type class. This is a function from type <code>a</code> to (<code>a -&gt; a</code>).</p>
<p>Yes, strange. In fact, in Haskell no function really has two arguments. Instead all functions have only one argument. But we will note that taking two arguments is equivalent to taking one argument and returning a function taking the second argument as a parameter.</p>
<p>More precisely <code>f 3 4</code> is equivalent to <code>(f 3) 4</code>. Note <code>f 3</code> is a function:</p>
<pre><code>f :: Num a =&gt; a -&gt; a -&gt; a
g :: Num a =&gt; a -&gt; a
g = f 3
g y ⇔ 3*3 + y*y</code></pre>
<p>Another notation exists for functions. The lambda notation allows us to create functions without assigning them a name. We call them anonymous functions. We could also have written:</p>
<pre><code>g = \y -&gt; 3*3 + y*y</code></pre>
<p>The <code>\</code> is used because it looks like <code>λ</code> and is ASCII.</p>
<p>If you are not used to functional programming your brain should be starting to heat up. It is time to make a real application.</p>
<p><a href="code/01_basic/10_Introduction/22_very_basic.lhs" class="cut">01_basic/10_Introduction/<strong>22_very_basic.lhs</strong> </a></p>
<hr />
<p><a href="code/01_basic/10_Introduction/23_very_basic.lhs" class="cut">01_basic/10_Introduction/<strong>23_very_basic.lhs</strong></a></p>
<p>But just before that, we should verify the type system works as expected:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb23"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb23-1" title="1"><span class="ot">f ::</span> <span class="dt">Num</span> a <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> a</a>
<a class="sourceLine" id="cb23-2" title="2">f x y <span class="ot">=</span> x<span class="op">*</span>x <span class="op">+</span> y<span class="op">*</span>y</a>
<a class="sourceLine" id="cb23-3" title="3"></a>
<a class="sourceLine" id="cb23-4" title="4">main <span class="ot">=</span> <span class="fu">print</span> (f <span class="dv">3</span> <span class="fl">2.4</span>)</a></code></pre></div>
</div>
<p>It works, because, <code>3</code> is a valid representation both for Fractional numbers like Float and for Integer. As <code>2.4</code> is a Fractional number, <code>3</code> is then interpreted as being also a Fractional number.</p>
<p><a href="code/01_basic/10_Introduction/23_very_basic.lhs" class="cut">01_basic/10_Introduction/<strong>23_very_basic.lhs</strong> </a></p>
<hr />
<p><a href="code/01_basic/10_Introduction/24_very_basic.lhs" class="cut">01_basic/10_Introduction/<strong>24_very_basic.lhs</strong></a></p>
<p>If we force our function to work with different types, it will fail:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb24"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb24-1" title="1"><span class="ot">f ::</span> <span class="dt">Num</span> a <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> a</a>
<a class="sourceLine" id="cb24-2" title="2">f x y <span class="ot">=</span> x<span class="op">*</span>x <span class="op">+</span> y<span class="op">*</span>y</a>
<a class="sourceLine" id="cb24-3" title="3"></a>
<a class="sourceLine" id="cb24-4" title="4"><span class="ot">x ::</span> <span class="dt">Int</span></a>
<a class="sourceLine" id="cb24-5" title="5">x <span class="ot">=</span> <span class="dv">3</span></a>
<a class="sourceLine" id="cb24-6" title="6"><span class="ot">y ::</span> <span class="dt">Float</span></a>
<a class="sourceLine" id="cb24-7" title="7">y <span class="ot">=</span> <span class="fl">2.4</span></a>
<a class="sourceLine" id="cb24-8" title="8"><span class="co">-- won't work because type x ≠ type y</span></a>
<a class="sourceLine" id="cb24-9" title="9">main <span class="ot">=</span> <span class="fu">print</span> (f x y)</a></code></pre></div>
</div>
<p>The compiler complains. The two parameters must have the same type.</p>
<p>If you believe that this is a bad idea, and that the compiler should make the transformation from one type to another for you, you should really watch this great (and funny) video: <a href="https://www.destroyallsoftware.com/talks/wat">WAT</a></p>
<p><a href="code/01_basic/10_Introduction/24_very_basic.lhs" class="cut">01_basic/10_Introduction/<strong>24_very_basic.lhs</strong> </a></p>
<h2 id="essential-haskell">
Essential Haskell
</h2>
<div>
<img src="../../../../Scratch/img/blog/Haskell-the-Hard-Way/kandinsky_gugg.jpg" alt="Kandinsky Gugg" />
</div>
<p>I suggest that you skim this part. Think of it as a reference. Haskell has a lot of features. A lot of information is missing here. Come back here if the notation feels strange.</p>
<p>I use the <code></code> symbol to state that two expression are equivalent. It is a meta notation, <code></code> does not exists in Haskell. I will also use <code></code> to show what the return value of an expression is.</p>
<h3 id="notations">
Notations
</h3>
<h5 id="arithmetic">
Arithmetic
</h5>
<pre><code>3 + 2 * 6 / 3 ⇔ 3 + ((2*6)/3)</code></pre>
<h5 id="logic">
Logic
</h5>
<pre><code>True || False ⇒ True
True &amp;&amp; False ⇒ False
True == False ⇒ False
True /= False ⇒ True (/=) is the operator for different</code></pre>
<h5 id="powers">
Powers
</h5>
<pre><code>x^n for n an integral (understand Int or Integer)
x**y for y any kind of number (Float for example)</code></pre>
<p><code>Integer</code> has no limit except the capacity of your machine:</p>
<pre><code>4^103
102844034832575377634685573909834406561420991602098741459288064</code></pre>
<p>Yeah! And also rational numbers FTW! But you need to import the module <code>Data.Ratio</code>:</p>
<pre><code>$ ghci
....
Prelude&gt; :m Data.Ratio
Data.Ratio&gt; (11 % 15) * (5 % 3)
11 % 9</code></pre>
<h5 id="lists">
Lists
</h5>
<pre><code>[] ⇔ empty list
[1,2,3] ⇔ List of integral
[&quot;foo&quot;,&quot;bar&quot;,&quot;baz&quot;] ⇔ List of String
1:[2,3] ⇔ [1,2,3], (:) prepend one element
1:2:[] ⇔ [1,2]
[1,2] ++ [3,4] ⇔ [1,2,3,4], (++) concatenate
[1,2,3] ++ [&quot;foo&quot;] ⇔ ERROR String ≠ Integral
[1..4] ⇔ [1,2,3,4]
[1,3..10] ⇔ [1,3,5,7,9]
[2,3,5,7,11..100] ⇔ ERROR! I am not so smart!
[10,9..1] ⇔ [10,9,8,7,6,5,4,3,2,1]</code></pre>
<h5 id="strings">
Strings
</h5>
<p>In Haskell strings are list of <code>Char</code>.</p>
<pre><code>'a' :: Char
&quot;a&quot; :: [Char]
&quot;&quot; ⇔ []
&quot;ab&quot; ⇔ ['a','b'] ⇔ 'a':&quot;b&quot; ⇔ 'a':['b'] ⇔ 'a':'b':[]
&quot;abc&quot;&quot;ab&quot;++&quot;c&quot;</code></pre>
<blockquote>
<p><em>Remark</em>: In real code you shouldnt use list of char to represent text. You should mostly use <code>Data.Text</code> instead. If you want to represent a stream of ASCII char, you should use <code>Data.ByteString</code>.</p>
</blockquote>
<h5 id="tuples">
Tuples
</h5>
<p>The type of couple is <code>(a,b)</code>. Elements in a tuple can have different types.</p>
<pre><code>-- All these tuples are valid
(2,&quot;foo&quot;)
(3,'a',[2,3])
((2,&quot;a&quot;),&quot;c&quot;,3)
fst (x,y) ⇒ x
snd (x,y) ⇒ y
fst (x,y,z) ⇒ ERROR: fst :: (a,b) -&gt; a
snd (x,y,z) ⇒ ERROR: snd :: (a,b) -&gt; b</code></pre>
<h5 id="deal-with-parentheses">
Deal with parentheses
</h5>
<p>To remove some parentheses you can use two functions: <code>($)</code> and <code>(.)</code>.</p>
<pre><code>-- By default:
f g h x ⇔ (((f g) h) x)
-- the $ replace parenthesis from the $
-- to the end of the expression
f g $ h x ⇔ f g (h x) ⇔ (f g) (h x)
f $ g h x ⇔ f (g h x) ⇔ f ((g h) x)
f $ g $ h x ⇔ f (g (h x))
-- (.) the composition function
(f . g) x ⇔ f (g x)
(f . g . h) x ⇔ f (g (h x))</code></pre>
<hr />
<p><a href="code/01_basic/20_Essential_Haskell/10a_Functions.lhs" class="cut">01_basic/20_Essential_Haskell/<strong>10a_Functions.lhs</strong></a></p>
<h3 id="useful-notations-for-functions">
Useful notations for functions
</h3>
<p>Just a reminder:</p>
<pre><code>x :: Int ⇔ x is of type Int
x :: a ⇔ x can be of any type
x :: Num a =&gt; a ⇔ x can be any type a
such that a belongs to Num type class
f :: a -&gt; b ⇔ f is a function from a to b
f :: a -&gt; b -&gt; c ⇔ f is a function from a to (b→c)
f :: (a -&gt; b) -&gt; c ⇔ f is a function from (a→b) to c</code></pre>
<p>Remember that defining the type of a function before its declaration isnt mandatory. Haskell infers the most general type for you. But it is considered a good practice to do so.</p>
<p><em>Infix notation</em></p>
<div class="codehighlight">
<div class="sourceCode" id="cb35"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb35-1" title="1"><span class="ot">square ::</span> <span class="dt">Num</span> a <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> a</a>
<a class="sourceLine" id="cb35-2" title="2">square x <span class="ot">=</span> x<span class="op">^</span><span class="dv">2</span></a></code></pre></div>
</div>
<p>Note <code>^</code> uses infix notation. For each infix operator there its associated prefix notation. You just have to put it inside parenthesis.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb36"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb36-1" title="1">square' x <span class="ot">=</span> (<span class="op">^</span>) x <span class="dv">2</span></a>
<a class="sourceLine" id="cb36-2" title="2"></a>
<a class="sourceLine" id="cb36-3" title="3">square'' x <span class="ot">=</span> (<span class="op">^</span><span class="dv">2</span>) x</a></code></pre></div>
</div>
<p>We can remove <code>x</code> in the left and right side! Its called η-reduction.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb37"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb37-1" title="1">square''' <span class="ot">=</span> (<span class="op">^</span><span class="dv">2</span>)</a></code></pre></div>
</div>
<p>Note we can declare functions with <code>'</code> in their name. Here:</p>
<blockquote>
<p><code>square</code><code>square'</code><code>square''</code><code>square'''</code></p>
</blockquote>
<p><em>Tests</em></p>
<p>An implementation of the absolute function.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb38"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb38-1" title="1"><span class="ot">absolute ::</span> (<span class="dt">Ord</span> a, <span class="dt">Num</span> a) <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> a</a>
<a class="sourceLine" id="cb38-2" title="2">absolute x <span class="ot">=</span> <span class="kw">if</span> x <span class="op">&gt;=</span> <span class="dv">0</span> <span class="kw">then</span> x <span class="kw">else</span> <span class="op">-</span>x</a></code></pre></div>
</div>
<p>Note: the <code>if .. then .. else</code> Haskell notation is more like the <code>¤?¤:¤</code> C operator. You cannot forget the <code>else</code>.</p>
<p>Another equivalent version:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb39"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb39-1" title="1">absolute' x</a>
<a class="sourceLine" id="cb39-2" title="2"> <span class="op">|</span> x <span class="op">&gt;=</span> <span class="dv">0</span> <span class="ot">=</span> x</a>
<a class="sourceLine" id="cb39-3" title="3"> <span class="op">|</span> <span class="fu">otherwise</span> <span class="ot">=</span> <span class="op">-</span>x</a></code></pre></div>
</div>
<blockquote>
<p>Notation warning: indentation is <em>important</em> in Haskell. Like in Python, bad indentation can break your code!</p>
</blockquote>
<div style="display:none">
<div class="codehighlight">
<div class="sourceCode" id="cb40"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb40-1" title="1">main <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb40-2" title="2"> <span class="fu">print</span> <span class="op">$</span> square <span class="dv">10</span></a>
<a class="sourceLine" id="cb40-3" title="3"> <span class="fu">print</span> <span class="op">$</span> square' <span class="dv">10</span></a>
<a class="sourceLine" id="cb40-4" title="4"> <span class="fu">print</span> <span class="op">$</span> square'' <span class="dv">10</span></a>
<a class="sourceLine" id="cb40-5" title="5"> <span class="fu">print</span> <span class="op">$</span> square''' <span class="dv">10</span></a>
<a class="sourceLine" id="cb40-6" title="6"> <span class="fu">print</span> <span class="op">$</span> absolute <span class="dv">10</span></a>
<a class="sourceLine" id="cb40-7" title="7"> <span class="fu">print</span> <span class="op">$</span> absolute (<span class="op">-</span><span class="dv">10</span>)</a>
<a class="sourceLine" id="cb40-8" title="8"> <span class="fu">print</span> <span class="op">$</span> absolute' <span class="dv">10</span></a>
<a class="sourceLine" id="cb40-9" title="9"> <span class="fu">print</span> <span class="op">$</span> absolute' (<span class="op">-</span><span class="dv">10</span>)</a></code></pre></div>
</div>
</div>
<p><a href="code/01_basic/20_Essential_Haskell/10a_Functions.lhs" class="cut">01_basic/20_Essential_Haskell/<strong>10a_Functions.lhs</strong> </a></p>
<h2 id="hard-part">
Hard Part
</h2>
<p>The hard part can now begin.</p>
<h3 id="functional-style">
Functional style
</h3>
<div>
<img src="../../../../Scratch/img/blog/Haskell-the-Hard-Way/hr_giger_biomechanicallandscape_500.jpg" alt="Biomechanical Landscape by H.R. Giger" />
</div>
<p>In this section, I will give a short example of the impressive refactoring ability provided by Haskell. We will select a problem and solve it in a standard imperative way. Then I will make the code evolve. The end result will be both more elegant and easier to adapt.</p>
<p>Lets solve the following problem:</p>
<blockquote>
<p>Given a list of integers, return the sum of the even numbers in the list.</p>
<p>example: <code>[1,2,3,4,5] ⇒ 2 + 4 ⇒ 6</code></p>
</blockquote>
<p>To show differences between functional and imperative approaches, Ill start by providing an imperative solution (in JavaScript):</p>
<div class="sourceCode" id="cb41"><pre class="sourceCode javascript"><code class="sourceCode javascript"><a class="sourceLine" id="cb41-1" title="1"><span class="kw">function</span> <span class="at">evenSum</span>(list) <span class="op">{</span></a>
<a class="sourceLine" id="cb41-2" title="2"> <span class="kw">var</span> result <span class="op">=</span> <span class="dv">0</span><span class="op">;</span></a>
<a class="sourceLine" id="cb41-3" title="3"> <span class="cf">for</span> (<span class="kw">var</span> i<span class="op">=</span><span class="dv">0</span><span class="op">;</span> i<span class="op">&lt;</span> <span class="va">list</span>.<span class="at">length</span> <span class="op">;</span> i<span class="op">++</span>) <span class="op">{</span></a>
<a class="sourceLine" id="cb41-4" title="4"> <span class="cf">if</span> (list[i] <span class="op">%</span> <span class="dv">2</span> <span class="op">==</span><span class="dv">0</span>) <span class="op">{</span></a>
<a class="sourceLine" id="cb41-5" title="5"> result <span class="op">+=</span> list[i]<span class="op">;</span></a>
<a class="sourceLine" id="cb41-6" title="6"> <span class="op">}</span></a>
<a class="sourceLine" id="cb41-7" title="7"> <span class="op">}</span></a>
<a class="sourceLine" id="cb41-8" title="8"> <span class="cf">return</span> result<span class="op">;</span></a>
<a class="sourceLine" id="cb41-9" title="9"><span class="op">}</span></a></code></pre></div>
<p>In Haskell, by contrast, we dont have variables or a for loop. One solution to achieve the same result without loops is to use recursion.</p>
<blockquote>
<p><em>Remark</em>: Recursion is generally perceived as slow in imperative languages. But this is generally not the case in functional programming. Most of the time Haskell will handle recursive functions efficiently.</p>
</blockquote>
<p>Here is a <code>C</code> version of the recursive function. Note that for simplicity I assume the int list ends with the first <code>0</code> value.</p>
<div class="sourceCode" id="cb42"><pre class="sourceCode c"><code class="sourceCode c"><a class="sourceLine" id="cb42-1" title="1"><span class="dt">int</span> evenSum(<span class="dt">int</span> *list) {</a>
<a class="sourceLine" id="cb42-2" title="2"> <span class="cf">return</span> accumSum(<span class="dv">0</span>,list);</a>
<a class="sourceLine" id="cb42-3" title="3">}</a>
<a class="sourceLine" id="cb42-4" title="4"></a>
<a class="sourceLine" id="cb42-5" title="5"><span class="dt">int</span> accumSum(<span class="dt">int</span> n, <span class="dt">int</span> *list) {</a>
<a class="sourceLine" id="cb42-6" title="6"> <span class="dt">int</span> x;</a>
<a class="sourceLine" id="cb42-7" title="7"> <span class="dt">int</span> *xs;</a>
<a class="sourceLine" id="cb42-8" title="8"> <span class="cf">if</span> (*list == <span class="dv">0</span>) { <span class="co">// if the list is empty</span></a>
<a class="sourceLine" id="cb42-9" title="9"> <span class="cf">return</span> n;</a>
<a class="sourceLine" id="cb42-10" title="10"> } <span class="cf">else</span> {</a>
<a class="sourceLine" id="cb42-11" title="11"> x = list[<span class="dv">0</span>]; <span class="co">// let x be the first element of the list</span></a>
<a class="sourceLine" id="cb42-12" title="12"> xs = list+<span class="dv">1</span>; <span class="co">// let xs be the list without x</span></a>
<a class="sourceLine" id="cb42-13" title="13"> <span class="cf">if</span> ( <span class="dv">0</span> == (x%<span class="dv">2</span>) ) { <span class="co">// if x is even</span></a>
<a class="sourceLine" id="cb42-14" title="14"> <span class="cf">return</span> accumSum(n+x, xs);</a>
<a class="sourceLine" id="cb42-15" title="15"> } <span class="cf">else</span> {</a>
<a class="sourceLine" id="cb42-16" title="16"> <span class="cf">return</span> accumSum(n, xs);</a>
<a class="sourceLine" id="cb42-17" title="17"> }</a>
<a class="sourceLine" id="cb42-18" title="18"> }</a>
<a class="sourceLine" id="cb42-19" title="19">}</a></code></pre></div>
<p>Keep this code in mind. We will translate it into Haskell. First, however, I need to introduce three simple but useful functions we will use:</p>
<div class="sourceCode" id="cb43"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb43-1" title="1"><span class="fu">even</span><span class="ot"> ::</span> <span class="dt">Integral</span> a <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Bool</span></a>
<a class="sourceLine" id="cb43-2" title="2"><span class="fu">head</span><span class="ot"> ::</span> [a] <span class="ot">-&gt;</span> a</a>
<a class="sourceLine" id="cb43-3" title="3"><span class="fu">tail</span><span class="ot"> ::</span> [a] <span class="ot">-&gt;</span> [a]</a></code></pre></div>
<p><code>even</code> verifies if a number is even.</p>
<div class="sourceCode" id="cb44"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb44-1" title="1"><span class="fu">even</span><span class="ot"> ::</span> <span class="dt">Integral</span> a <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Bool</span></a>
<a class="sourceLine" id="cb44-2" title="2"><span class="fu">even</span> <span class="dv">3</span> <span class="ot"></span> <span class="dt">False</span></a>
<a class="sourceLine" id="cb44-3" title="3"><span class="fu">even</span> <span class="dv">2</span> <span class="ot"></span> <span class="dt">True</span></a></code></pre></div>
<p><code>head</code> returns the first element of a list:</p>
<div class="sourceCode" id="cb45"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb45-1" title="1"><span class="fu">head</span><span class="ot"> ::</span> [a] <span class="ot">-&gt;</span> a</a>
<a class="sourceLine" id="cb45-2" title="2"><span class="fu">head</span> [<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>] <span class="ot"></span> <span class="dv">1</span></a>
<a class="sourceLine" id="cb45-3" title="3"><span class="fu">head</span> [] <span class="ot"></span> <span class="dt">ERROR</span></a></code></pre></div>
<p><code>tail</code> returns all elements of a list, except the first:</p>
<div class="sourceCode" id="cb46"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb46-1" title="1"><span class="fu">tail</span><span class="ot"> ::</span> [a] <span class="ot">-&gt;</span> [a]</a>
<a class="sourceLine" id="cb46-2" title="2"><span class="fu">tail</span> [<span class="dv">1</span>,<span class="dv">2</span>,<span class="dv">3</span>] <span class="ot"></span> [<span class="dv">2</span>,<span class="dv">3</span>]</a>
<a class="sourceLine" id="cb46-3" title="3"><span class="fu">tail</span> [<span class="dv">3</span>] <span class="ot"></span> []</a>
<a class="sourceLine" id="cb46-4" title="4"><span class="fu">tail</span> [] <span class="ot"></span> <span class="dt">ERROR</span></a></code></pre></div>
<p>Note that for any non empty list <code>l</code>, <code>l ⇔ (head l):(tail l)</code></p>
<hr />
<p><a href="code/02_Hard_Part/11_Functions.lhs" class="cut">02_Hard_Part/<strong>11_Functions.lhs</strong></a></p>
<p>The first Haskell solution. The function <code>evenSum</code> returns the sum of all even numbers in a list:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb47"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb47-1" title="1"><span class="co">-- Version 1</span></a>
<a class="sourceLine" id="cb47-2" title="2"><span class="ot">evenSum ::</span> [<span class="dt">Integer</span>] <span class="ot">-&gt;</span> <span class="dt">Integer</span></a>
<a class="sourceLine" id="cb47-3" title="3"></a>
<a class="sourceLine" id="cb47-4" title="4">evenSum l <span class="ot">=</span> accumSum <span class="dv">0</span> l</a>
<a class="sourceLine" id="cb47-5" title="5"></a>
<a class="sourceLine" id="cb47-6" title="6">accumSum n l <span class="ot">=</span> <span class="kw">if</span> l <span class="op">==</span> []</a>
<a class="sourceLine" id="cb47-7" title="7"> <span class="kw">then</span> n</a>
<a class="sourceLine" id="cb47-8" title="8"> <span class="kw">else</span> <span class="kw">let</span> x <span class="ot">=</span> <span class="fu">head</span> l</a>
<a class="sourceLine" id="cb47-9" title="9"> xs <span class="ot">=</span> <span class="fu">tail</span> l</a>
<a class="sourceLine" id="cb47-10" title="10"> <span class="kw">in</span> <span class="kw">if</span> <span class="fu">even</span> x</a>
<a class="sourceLine" id="cb47-11" title="11"> <span class="kw">then</span> accumSum (n<span class="op">+</span>x) xs</a>
<a class="sourceLine" id="cb47-12" title="12"> <span class="kw">else</span> accumSum n xs</a></code></pre></div>
</div>
<p>To test a function you can use <code>ghci</code>:</p>
<pre>
% ghci
<span class="low">GHCi, version 7.0.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude&gt;</span> :load 11_Functions.lhs
<span class="low">[1 of 1] Compiling Main ( 11_Functions.lhs, interpreted )
Ok, modules loaded: Main.
*Main&gt;</span> evenSum [1..5]
6
</pre>
<p>Here is an example of execution<a href="#fn2" class="footnote-ref" id="fnref2"><sup>2</sup></a>:</p>
<pre>
*Main> evenSum [1..5]
accumSum 0 [1,2,3,4,5]
<span class="yellow">1 is odd</span>
accumSum 0 [2,3,4,5]
<span class="yellow">2 is even</span>
accumSum (0+2) [3,4,5]
<span class="yellow">3 is odd</span>
accumSum (0+2) [4,5]
<span class="yellow">2 is even</span>
accumSum (0+2+4) [5]
<span class="yellow">5 is odd</span>
accumSum (0+2+4) []
<span class="yellow">l == []</span>
0+2+4
0+6
6
</pre>
<p>Coming from an imperative language all should seem right. In fact, many things can be improved here. First, we can generalize the type.</p>
<div class="sourceCode" id="cb48"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb48-1" title="1"><span class="ot">evenSum ::</span> <span class="dt">Integral</span> a <span class="ot">=&gt;</span> [a] <span class="ot">-&gt;</span> a</a></code></pre></div>
<div style="display:none">
<div class="codehighlight">
<div class="sourceCode" id="cb49"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb49-1" title="1">main <span class="ot">=</span> <span class="kw">do</span> <span class="fu">print</span> <span class="op">$</span> evenSum [<span class="dv">1</span><span class="op">..</span><span class="dv">10</span>]</a></code></pre></div>
</div>
</div>
<p><a href="code/02_Hard_Part/11_Functions.lhs" class="cut">02_Hard_Part/<strong>11_Functions.lhs</strong> </a></p>
<hr />
<p><a href="code/02_Hard_Part/12_Functions.lhs" class="cut">02_Hard_Part/<strong>12_Functions.lhs</strong></a></p>
<p>Next, we can use sub functions using <code>where</code> or <code>let</code>. This way our <code>accumSum</code> function wont pollute the namespace of our module.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb50"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb50-1" title="1"><span class="co">-- Version 2</span></a>
<a class="sourceLine" id="cb50-2" title="2"><span class="ot">evenSum ::</span> <span class="dt">Integral</span> a <span class="ot">=&gt;</span> [a] <span class="ot">-&gt;</span> a</a>
<a class="sourceLine" id="cb50-3" title="3"></a>
<a class="sourceLine" id="cb50-4" title="4">evenSum l <span class="ot">=</span> accumSum <span class="dv">0</span> l</a>
<a class="sourceLine" id="cb50-5" title="5"> <span class="kw">where</span> accumSum n l <span class="ot">=</span></a>
<a class="sourceLine" id="cb50-6" title="6"> <span class="kw">if</span> l <span class="op">==</span> []</a>
<a class="sourceLine" id="cb50-7" title="7"> <span class="kw">then</span> n</a>
<a class="sourceLine" id="cb50-8" title="8"> <span class="kw">else</span> <span class="kw">let</span> x <span class="ot">=</span> <span class="fu">head</span> l</a>
<a class="sourceLine" id="cb50-9" title="9"> xs <span class="ot">=</span> <span class="fu">tail</span> l</a>
<a class="sourceLine" id="cb50-10" title="10"> <span class="kw">in</span> <span class="kw">if</span> <span class="fu">even</span> x</a>
<a class="sourceLine" id="cb50-11" title="11"> <span class="kw">then</span> accumSum (n<span class="op">+</span>x) xs</a>
<a class="sourceLine" id="cb50-12" title="12"> <span class="kw">else</span> accumSum n xs</a></code></pre></div>
</div>
<div style="display:none">
<div class="codehighlight">
<div class="sourceCode" id="cb51"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb51-1" title="1">main <span class="ot">=</span> <span class="fu">print</span> <span class="op">$</span> evenSum [<span class="dv">1</span><span class="op">..</span><span class="dv">10</span>]</a></code></pre></div>
</div>
</div>
<p><a href="code/02_Hard_Part/12_Functions.lhs" class="cut">02_Hard_Part/<strong>12_Functions.lhs</strong> </a></p>
<hr />
<p><a href="code/02_Hard_Part/13_Functions.lhs" class="cut">02_Hard_Part/<strong>13_Functions.lhs</strong></a></p>
<p>Next, we can use pattern matching.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb52"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb52-1" title="1"><span class="co">-- Version 3</span></a>
<a class="sourceLine" id="cb52-2" title="2">evenSum l <span class="ot">=</span> accumSum <span class="dv">0</span> l</a>
<a class="sourceLine" id="cb52-3" title="3"> <span class="kw">where</span></a>
<a class="sourceLine" id="cb52-4" title="4"> accumSum n [] <span class="ot">=</span> n</a>
<a class="sourceLine" id="cb52-5" title="5"> accumSum n (x<span class="op">:</span>xs) <span class="ot">=</span></a>
<a class="sourceLine" id="cb52-6" title="6"> <span class="kw">if</span> <span class="fu">even</span> x</a>
<a class="sourceLine" id="cb52-7" title="7"> <span class="kw">then</span> accumSum (n<span class="op">+</span>x) xs</a>
<a class="sourceLine" id="cb52-8" title="8"> <span class="kw">else</span> accumSum n xs</a></code></pre></div>
</div>
<p>What is pattern matching? Use values instead of general parameter names<a href="#fn3" class="footnote-ref" id="fnref3"><sup>3</sup></a>.</p>
<p>Instead of saying: <code>foo l = if l == [] then &lt;x&gt; else &lt;y&gt;</code> You simply state:</p>
<div class="sourceCode" id="cb53"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb53-1" title="1">foo [] <span class="ot">=</span> <span class="op">&lt;</span>x<span class="op">&gt;</span></a>
<a class="sourceLine" id="cb53-2" title="2">foo l <span class="ot">=</span> <span class="op">&lt;</span>y<span class="op">&gt;</span></a></code></pre></div>
<p>But pattern matching goes even further. It is also able to inspect the inner data of a complex value. We can replace</p>
<div class="sourceCode" id="cb54"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb54-1" title="1">foo l <span class="ot">=</span> <span class="kw">let</span> x <span class="ot">=</span> <span class="fu">head</span> l</a>
<a class="sourceLine" id="cb54-2" title="2"> xs <span class="ot">=</span> <span class="fu">tail</span> l</a>
<a class="sourceLine" id="cb54-3" title="3"> <span class="kw">in</span> <span class="kw">if</span> <span class="fu">even</span> x</a>
<a class="sourceLine" id="cb54-4" title="4"> <span class="kw">then</span> foo (n<span class="op">+</span>x) xs</a>
<a class="sourceLine" id="cb54-5" title="5"> <span class="kw">else</span> foo n xs</a></code></pre></div>
<p>with</p>
<div class="sourceCode" id="cb55"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb55-1" title="1">foo (x<span class="op">:</span>xs) <span class="ot">=</span> <span class="kw">if</span> <span class="fu">even</span> x</a>
<a class="sourceLine" id="cb55-2" title="2"> <span class="kw">then</span> foo (n<span class="op">+</span>x) xs</a>
<a class="sourceLine" id="cb55-3" title="3"> <span class="kw">else</span> foo n xs</a></code></pre></div>
<p>This is a very useful feature. It makes our code both terser and easier to read.</p>
<div style="display:none">
<div class="codehighlight">
<div class="sourceCode" id="cb56"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb56-1" title="1">main <span class="ot">=</span> <span class="fu">print</span> <span class="op">$</span> evenSum [<span class="dv">1</span><span class="op">..</span><span class="dv">10</span>]</a></code></pre></div>
</div>
</div>
<p><a href="code/02_Hard_Part/13_Functions.lhs" class="cut">02_Hard_Part/<strong>13_Functions.lhs</strong> </a></p>
<hr />
<p><a href="code/02_Hard_Part/14_Functions.lhs" class="cut">02_Hard_Part/<strong>14_Functions.lhs</strong></a></p>
<p>In Haskell you can simplify function definitions by η-reducing them. For example, instead of writing:</p>
<div class="sourceCode" id="cb57"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb57-1" title="1">f x <span class="ot">=</span> (some expresion) x</a></code></pre></div>
<p>you can simply write</p>
<div class="sourceCode" id="cb58"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb58-1" title="1">f <span class="ot">=</span> some expression</a></code></pre></div>
<p>We use this method to remove the <code>l</code>:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb59"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb59-1" title="1"><span class="co">-- Version 4</span></a>
<a class="sourceLine" id="cb59-2" title="2"><span class="ot">evenSum ::</span> <span class="dt">Integral</span> a <span class="ot">=&gt;</span> [a] <span class="ot">-&gt;</span> a</a>
<a class="sourceLine" id="cb59-3" title="3"></a>
<a class="sourceLine" id="cb59-4" title="4">evenSum <span class="ot">=</span> accumSum <span class="dv">0</span></a>
<a class="sourceLine" id="cb59-5" title="5"> <span class="kw">where</span></a>
<a class="sourceLine" id="cb59-6" title="6"> accumSum n [] <span class="ot">=</span> n</a>
<a class="sourceLine" id="cb59-7" title="7"> accumSum n (x<span class="op">:</span>xs) <span class="ot">=</span></a>
<a class="sourceLine" id="cb59-8" title="8"> <span class="kw">if</span> <span class="fu">even</span> x</a>
<a class="sourceLine" id="cb59-9" title="9"> <span class="kw">then</span> accumSum (n<span class="op">+</span>x) xs</a>
<a class="sourceLine" id="cb59-10" title="10"> <span class="kw">else</span> accumSum n xs</a></code></pre></div>
</div>
<div style="display:none">
<div class="codehighlight">
<div class="sourceCode" id="cb60"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb60-1" title="1">main <span class="ot">=</span> <span class="fu">print</span> <span class="op">$</span> evenSum [<span class="dv">1</span><span class="op">..</span><span class="dv">10</span>]</a></code></pre></div>
</div>
</div>
<p><a href="code/02_Hard_Part/14_Functions.lhs" class="cut">02_Hard_Part/<strong>14_Functions.lhs</strong> </a></p>
<hr />
<p><a href="code/02_Hard_Part/15_Functions.lhs" class="cut">02_Hard_Part/<strong>15_Functions.lhs</strong></a></p>
<h4 id="higher-order-functions">
Higher Order Functions
</h4>
<div>
<img src="../../../../Scratch/img/blog/Haskell-the-Hard-Way/escher_polygon.png" alt="Escher" />
</div>
<p>To make things even better we should use higher order functions. What are these beasts? Higher order functions are functions taking functions as parameters.</p>
<p>Here are some examples:</p>
<div class="sourceCode" id="cb61"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb61-1" title="1"><span class="fu">filter</span><span class="ot"> ::</span> (a <span class="ot">-&gt;</span> <span class="dt">Bool</span>) <span class="ot">-&gt;</span> [a] <span class="ot">-&gt;</span> [a]</a>
<a class="sourceLine" id="cb61-2" title="2"><span class="fu">map</span><span class="ot"> ::</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> [a] <span class="ot">-&gt;</span> [b]</a>
<a class="sourceLine" id="cb61-3" title="3"><span class="fu">foldl</span><span class="ot"> ::</span> (a <span class="ot">-&gt;</span> b <span class="ot">-&gt;</span> a) <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> [b] <span class="ot">-&gt;</span> a</a></code></pre></div>
<p>Lets proceed by small steps.</p>
<div class="sourceCode" id="cb62"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb62-1" title="1"><span class="co">-- Version 5</span></a>
<a class="sourceLine" id="cb62-2" title="2">evenSum l <span class="ot">=</span> mysum <span class="dv">0</span> (<span class="fu">filter</span> <span class="fu">even</span> l)</a>
<a class="sourceLine" id="cb62-3" title="3"> <span class="kw">where</span></a>
<a class="sourceLine" id="cb62-4" title="4"> mysum n [] <span class="ot">=</span> n</a>
<a class="sourceLine" id="cb62-5" title="5"> mysum n (x<span class="op">:</span>xs) <span class="ot">=</span> mysum (n<span class="op">+</span>x) xs</a></code></pre></div>
<p>where</p>
<div class="sourceCode" id="cb63"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb63-1" title="1"><span class="fu">filter</span> <span class="fu">even</span> [<span class="dv">1</span><span class="op">..</span><span class="dv">10</span>] ⇔ [<span class="dv">2</span>,<span class="dv">4</span>,<span class="dv">6</span>,<span class="dv">8</span>,<span class="dv">10</span>]</a></code></pre></div>
<p>The function <code>filter</code> takes a function of type (<code>a -&gt; Bool</code>) and a list of type <code>[a]</code>. It returns a list containing only elements for which the function returned <code>true</code>.</p>
<p>Our next step is to use another technique to accomplish the same thing as a loop. We will use the <code>foldl</code> function to accumulate a value as we pass through the list. The function <code>foldl</code> captures a general coding pattern:</p>
<pre>
myfunc list = foo <span class="blue">initialValue</span> <span class="green">list</span>
foo accumulated [] = accumulated
foo tmpValue (x:xs) = foo (<span class="yellow">bar</span> tmpValue x) xs
</pre>
<p>Which can be replaced by:</p>
<pre>
myfunc list = foldl <span class="yellow">bar</span> <span class="blue">initialValue</span> <span class="green">list</span>
</pre>
<p>If you really want to know how the magic works, here is the definition of <code>foldl</code>:</p>
<div class="sourceCode" id="cb64"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb64-1" title="1"><span class="fu">foldl</span> f z [] <span class="ot">=</span> z</a>
<a class="sourceLine" id="cb64-2" title="2"><span class="fu">foldl</span> f z (x<span class="op">:</span>xs) <span class="ot">=</span> <span class="fu">foldl</span> f (f z x) xs</a></code></pre></div>
<div class="sourceCode" id="cb65"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb65-1" title="1"><span class="fu">foldl</span> f z [x1,<span class="op">...</span>xn]</a>
<a class="sourceLine" id="cb65-2" title="2">⇔ f (<span class="op">...</span> (f (f z x1) x2) <span class="op">...</span>) xn</a></code></pre></div>
<p>But as Haskell is lazy, it doesnt evaluate <code>(f z x)</code> and simply pushes it onto the stack. This is why we generally use <code>foldl'</code> instead of <code>foldl</code>; <code>foldl'</code> is a <em>strict</em> version of <code>foldl</code>. If you dont understand what lazy and strict means, dont worry, just follow the code as if <code>foldl</code> and <code>foldl'</code> were identical.</p>
<p>Now our new version of <code>evenSum</code> becomes:</p>
<div class="sourceCode" id="cb66"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb66-1" title="1"><span class="co">-- Version 6</span></a>
<a class="sourceLine" id="cb66-2" title="2"><span class="co">-- foldl' isn't accessible by default</span></a>
<a class="sourceLine" id="cb66-3" title="3"><span class="co">-- we need to import it from the module Data.List</span></a>
<a class="sourceLine" id="cb66-4" title="4"><span class="kw">import</span> <span class="dt">Data.List</span></a>
<a class="sourceLine" id="cb66-5" title="5">evenSum l <span class="ot">=</span> foldl' mysum <span class="dv">0</span> (<span class="fu">filter</span> <span class="fu">even</span> l)</a>
<a class="sourceLine" id="cb66-6" title="6"> <span class="kw">where</span> mysum acc value <span class="ot">=</span> acc <span class="op">+</span> value</a></code></pre></div>
<p>We can also simplify this by using directly a lambda notation. This way we dont have to create the temporary name <code>mysum</code>.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb67"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb67-1" title="1"><span class="co">-- Version 7</span></a>
<a class="sourceLine" id="cb67-2" title="2"><span class="co">-- Generally it is considered a good practice</span></a>
<a class="sourceLine" id="cb67-3" title="3"><span class="co">-- to import only the necessary function(s)</span></a>
<a class="sourceLine" id="cb67-4" title="4"><span class="kw">import</span> <span class="dt">Data.List</span> (foldl')</a>
<a class="sourceLine" id="cb67-5" title="5">evenSum l <span class="ot">=</span> foldl' (\x y <span class="ot">-&gt;</span> x<span class="op">+</span>y) <span class="dv">0</span> (<span class="fu">filter</span> <span class="fu">even</span> l)</a></code></pre></div>
</div>
<p>And of course, we note that</p>
<div class="sourceCode" id="cb68"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb68-1" title="1">(\x y <span class="ot">-&gt;</span> x<span class="op">+</span>y) ⇔ (<span class="op">+</span>)</a></code></pre></div>
<div style="display:none">
<div class="codehighlight">
<div class="sourceCode" id="cb69"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb69-1" title="1">main <span class="ot">=</span> <span class="fu">print</span> <span class="op">$</span> evenSum [<span class="dv">1</span><span class="op">..</span><span class="dv">10</span>]</a></code></pre></div>
</div>
</div>
<p><a href="code/02_Hard_Part/15_Functions.lhs" class="cut">02_Hard_Part/<strong>15_Functions.lhs</strong> </a></p>
<hr />
<p><a href="code/02_Hard_Part/16_Functions.lhs" class="cut">02_Hard_Part/<strong>16_Functions.lhs</strong></a></p>
<p>Finally</p>
<div class="sourceCode" id="cb70"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb70-1" title="1"><span class="co">-- Version 8</span></a>
<a class="sourceLine" id="cb70-2" title="2"><span class="kw">import</span> <span class="dt">Data.List</span> (foldl')</a>
<a class="sourceLine" id="cb70-3" title="3"><span class="ot">evenSum ::</span> <span class="dt">Integral</span> a <span class="ot">=&gt;</span> [a] <span class="ot">-&gt;</span> a</a>
<a class="sourceLine" id="cb70-4" title="4">evenSum l <span class="ot">=</span> foldl' (<span class="op">+</span>) <span class="dv">0</span> (<span class="fu">filter</span> <span class="fu">even</span> l)</a></code></pre></div>
<p><code>foldl'</code> isnt the easiest function to grasp. If you are not used to it, you should study it a bit.</p>
<p>To help you understand whats going on here, lets look at a step by step evaluation:</p>
<pre>
<span class="yellow">evenSum [1,2,3,4]</span>
⇒ foldl' (+) 0 (<span class="yellow">filter even [1,2,3,4]</span>)
<span class="yellow">foldl' (+) 0 <span class="blue">[2,4]</span></span>
<span class="blue">foldl' (+) (<span class="yellow">0+2</span>) [4]</span>
<span class="yellow">foldl' (+) <span class="blue">2</span> [4]</span>
<span class="blue">foldl' (+) (<span class="yellow">2+4</span>) []</span>
<span class="yellow">foldl' (+) <span class="blue">6</span> []</span>
<span class="blue">6</span>
</pre>
<p>Another useful higher order function is <code>(.)</code>. The <code>(.)</code> function corresponds to mathematical composition.</p>
<div class="sourceCode" id="cb71"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb71-1" title="1">(f <span class="op">.</span> g <span class="op">.</span> h) x ⇔ f ( g (h x))</a></code></pre></div>
<p>We can take advantage of this operator to η-reduce our function:</p>
<div class="sourceCode" id="cb72"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb72-1" title="1"><span class="co">-- Version 9</span></a>
<a class="sourceLine" id="cb72-2" title="2"><span class="kw">import</span> <span class="dt">Data.List</span> (foldl')</a>
<a class="sourceLine" id="cb72-3" title="3"><span class="ot">evenSum ::</span> <span class="dt">Integral</span> a <span class="ot">=&gt;</span> [a] <span class="ot">-&gt;</span> a</a>
<a class="sourceLine" id="cb72-4" title="4">evenSum <span class="ot">=</span> (foldl' (<span class="op">+</span>) <span class="dv">0</span>) <span class="op">.</span> (<span class="fu">filter</span> <span class="fu">even</span>)</a></code></pre></div>
<p>Also, we could rename some parts to make it clearer:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb73"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb73-1" title="1"><span class="co">-- Version 10</span></a>
<a class="sourceLine" id="cb73-2" title="2"><span class="kw">import</span> <span class="dt">Data.List</span> (foldl')</a>
<a class="sourceLine" id="cb73-3" title="3"><span class="ot">sum' ::</span> (<span class="dt">Num</span> a) <span class="ot">=&gt;</span> [a] <span class="ot">-&gt;</span> a</a>
<a class="sourceLine" id="cb73-4" title="4">sum' <span class="ot">=</span> foldl' (<span class="op">+</span>) <span class="dv">0</span></a>
<a class="sourceLine" id="cb73-5" title="5"><span class="ot">evenSum ::</span> <span class="dt">Integral</span> a <span class="ot">=&gt;</span> [a] <span class="ot">-&gt;</span> a</a>
<a class="sourceLine" id="cb73-6" title="6">evenSum <span class="ot">=</span> sum' <span class="op">.</span> (<span class="fu">filter</span> <span class="fu">even</span>)</a></code></pre></div>
</div>
<p>It is time to discuss the direction our code has moved as we introduced more functional idioms. What did we gain by using higher order functions?</p>
<p>At first, you might think the main difference is terseness. But in fact, it has more to do with better thinking. Suppose we want to modify our function slightly, for example, to get the sum of all even squares of elements of the list.</p>
<pre><code>[1,2,3,4] ▷ [1,4,9,16] ▷ [4,16] ▷ 20</code></pre>
<p>Updating version 10 is extremely easy:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb75"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb75-1" title="1">squareEvenSum <span class="ot">=</span> sum' <span class="op">.</span> (<span class="fu">filter</span> <span class="fu">even</span>) <span class="op">.</span> (<span class="fu">map</span> (<span class="op">^</span><span class="dv">2</span>))</a>
<a class="sourceLine" id="cb75-2" title="2">squareEvenSum' <span class="ot">=</span> evenSum <span class="op">.</span> (<span class="fu">map</span> (<span class="op">^</span><span class="dv">2</span>))</a></code></pre></div>
</div>
<p>We just had to add another “transformation function”[^0216].</p>
<pre><code>map (^2) [1,2,3,4] ⇔ [1,4,9,16]</code></pre>
<p>The <code>map</code> function simply applies a function to all the elements of a list.</p>
<p>We didnt have to modify anything <em>inside</em> the function definition. This makes the code more modular. But in addition you can think more mathematically about your function. You can also use your function interchangably with others, as needed. That is, you can compose, map, fold, filter using your new function.</p>
<p>Modifying version 1 is left as an exercise to the reader ☺.</p>
<p>If you believe we have reached the end of generalization, then know you are very wrong. For example, there is a way to not only use this function on lists but on any recursive type. If you want to know how, I suggest you to read this quite fun article: <a href="http://eprints.eemcs.utwente.nl/7281/01/db-utwente-40501F46.pdf">Functional Programming with Bananas, Lenses, Envelopes and Barbed Wire by Meijer, Fokkinga and Paterson</a>.</p>
<p>This example should show you how great pure functional programming is. Unfortunately, using pure functional programming isnt well suited to all usages. Or at least such a language hasnt been found yet.</p>
<p>One of the great powers of Haskell is the ability to create DSLs (Domain Specific Language) making it easy to change the programming paradigm.</p>
<p>In fact, Haskell is also great when you want to write imperative style programming. Understanding this was really hard for me to grasp when first learning Haskell. A lot of effort tends to go into explaining the superiority of the functional approach. Then when you start using an imperative style with Haskell, it can be hard to understand when and how to use it.</p>
<p>But before talking about this Haskell super-power, we must talk about another essential aspect of Haskell: <em>Types</em>.</p>
<div style="display:none">
<div class="codehighlight">
<div class="sourceCode" id="cb77"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb77-1" title="1">main <span class="ot">=</span> <span class="fu">print</span> <span class="op">$</span> evenSum [<span class="dv">1</span><span class="op">..</span><span class="dv">10</span>]</a></code></pre></div>
</div>
</div>
<p><a href="code/02_Hard_Part/16_Functions.lhs" class="cut">02_Hard_Part/<strong>16_Functions.lhs</strong> </a></p>
<h3 id="types">
Types
</h3>
<div>
<img src="../../../../Scratch/img/blog/Haskell-the-Hard-Way/salvador-dali-the-madonna-of-port-lligat.jpg" alt="Dali, the madonna of port Lligat" />
</div>
<blockquote>
<p><span class="sc"><abbr title="Too long; didn't read">tl;dr</abbr>: </span></p>
<ul>
<li><code>type Name = AnotherType</code> is just an alias and the compiler doesnt mark any difference between <code>Name</code> and <code>AnotherType</code>.</li>
<li><code>data Name = NameConstructor AnotherType</code> does mark a difference.</li>
<li><code>data</code> can construct structures which can be recursives.</li>
<li><code>deriving</code> is magic and creates functions for you.</li>
</ul>
</blockquote>
<p>In Haskell, types are strong and static.</p>
<p>Why is this important? It will help you <em>greatly</em> to avoid mistakes. In Haskell, most bugs are caught during the compilation of your program. And the main reason is because of the type inference during compilation. Type inference makes it easy to detect where you used the wrong parameter at the wrong place, for example.</p>
<h4 id="type-inference">
Type inference
</h4>
<p>Static typing is generally essential for fast execution. But most statically typed languages are bad at generalizing concepts. Haskells saving grace is that it can <em>infer</em> types.</p>
<p>Here is a simple example, the <code>square</code> function in Haskell:</p>
<div class="sourceCode" id="cb78"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb78-1" title="1">square x <span class="ot">=</span> x <span class="op">*</span> x</a></code></pre></div>
<p>This function can <code>square</code> any Numeral type. You can provide <code>square</code> with an <code>Int</code>, an <code>Integer</code>, a <code>Float</code> a <code>Fractional</code> and even <code>Complex</code>. Proof by example:</p>
<pre><code>% ghci
GHCi, version 7.0.4:
...
Prelude&gt; let square x = x*x
Prelude&gt; square 2
4
Prelude&gt; square 2.1
4.41
Prelude&gt; -- load the Data.Complex module
Prelude&gt; :m Data.Complex
Prelude Data.Complex&gt; square (2 :+ 1)
3.0 :+ 4.0</code></pre>
<p><code>x :+ y</code> is the notation for the complex (<i>x + iy</i>).</p>
<p>Now compare with the amount of code necessary in C:</p>
<div class="sourceCode" id="cb80"><pre class="sourceCode c"><code class="sourceCode c"><a class="sourceLine" id="cb80-1" title="1"><span class="dt">int</span> int_square(<span class="dt">int</span> x) { <span class="cf">return</span> x*x; }</a>
<a class="sourceLine" id="cb80-2" title="2"></a>
<a class="sourceLine" id="cb80-3" title="3"><span class="dt">float</span> float_square(<span class="dt">float</span> x) {<span class="cf">return</span> x*x; }</a>
<a class="sourceLine" id="cb80-4" title="4"></a>
<a class="sourceLine" id="cb80-5" title="5"><span class="dt">complex</span> complex_square (<span class="dt">complex</span> z) {</a>
<a class="sourceLine" id="cb80-6" title="6"> <span class="dt">complex</span> tmp;</a>
<a class="sourceLine" id="cb80-7" title="7"> tmp.real = z.real * z.real - z.img * z.img;</a>
<a class="sourceLine" id="cb80-8" title="8"> tmp.img = <span class="dv">2</span> * z.img * z.real;</a>
<a class="sourceLine" id="cb80-9" title="9">}</a>
<a class="sourceLine" id="cb80-10" title="10"></a>
<a class="sourceLine" id="cb80-11" title="11"><span class="dt">complex</span> x,y;</a>
<a class="sourceLine" id="cb80-12" title="12">y = complex_square(x);</a></code></pre></div>
<p>For each type, you need to write a new function. The only way to work around this problem is to use some meta-programming trick, for example using the pre-processor. In C++ there is a better way, C++ templates:</p>
<pre class="{.c++}"><code>#include &lt;iostream&gt;
#include &lt;complex&gt;
using namespace std;
template&lt;typename T&gt;
T square(T x)
{
return x*x;
}
int main() {
// int
int sqr_of_five = square(5);
cout &lt;&lt; sqr_of_five &lt;&lt; endl;
// double
cout &lt;&lt; (double)square(5.3) &lt;&lt; endl;
// complex
cout &lt;&lt; square( complex&lt;double&gt;(5,3) )
&lt;&lt; endl;
return 0;
}</code></pre>
<p>C++ does a far better job than C in this regard. But for more complex functions the syntax can be hard to follow: see <a href="http://bartoszmilewski.com/2009/10/21/what-does-haskell-have-to-do-with-c/">this article</a> for example.</p>
<p>In C++ you must declare that a function can work with different types. In Haskell, the opposite is the case. The function will be as general as possible by default.</p>
<p>Type inference gives Haskell the feeling of freedom that dynamically typed languages provide. But unlike dynamically typed languages, most errors are caught before run time. Generally, in Haskell:</p>
<blockquote>
<p>“if it compiles it certainly does what you intended”</p>
</blockquote>
<hr />
<p><a href="code/02_Hard_Part/21_Types.lhs" class="cut">02_Hard_Part/<strong>21_Types.lhs</strong></a></p>
<h4 id="type-construction">
Type construction
</h4>
<p>You can construct your own types. First, you can use aliases or type synonyms.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb82"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb82-1" title="1"><span class="kw">type</span> <span class="dt">Name</span> <span class="ot">=</span> <span class="dt">String</span></a>
<a class="sourceLine" id="cb82-2" title="2"><span class="kw">type</span> <span class="dt">Color</span> <span class="ot">=</span> <span class="dt">String</span></a>
<a class="sourceLine" id="cb82-3" title="3"></a>
<a class="sourceLine" id="cb82-4" title="4"><span class="ot">showInfos ::</span> <span class="dt">Name</span> <span class="ot">-&gt;</span> <span class="dt">Color</span> <span class="ot">-&gt;</span> <span class="dt">String</span></a>
<a class="sourceLine" id="cb82-5" title="5">showInfos name color <span class="ot">=</span> <span class="st">&quot;Name: &quot;</span> <span class="op">++</span> name</a>
<a class="sourceLine" id="cb82-6" title="6"> <span class="op">++</span> <span class="st">&quot;, Color: &quot;</span> <span class="op">++</span> color</a>
<a class="sourceLine" id="cb82-7" title="7"><span class="ot">name ::</span> <span class="dt">Name</span></a>
<a class="sourceLine" id="cb82-8" title="8">name <span class="ot">=</span> <span class="st">&quot;Robin&quot;</span></a>
<a class="sourceLine" id="cb82-9" title="9"><span class="ot">color ::</span> <span class="dt">Color</span></a>
<a class="sourceLine" id="cb82-10" title="10">color <span class="ot">=</span> <span class="st">&quot;Blue&quot;</span></a>
<a class="sourceLine" id="cb82-11" title="11">main <span class="ot">=</span> <span class="fu">putStrLn</span> <span class="op">$</span> showInfos name color</a></code></pre></div>
</div>
<p><a href="code/02_Hard_Part/21_Types.lhs" class="cut">02_Hard_Part/<strong>21_Types.lhs</strong> </a></p>
<hr />
<p><a href="code/02_Hard_Part/22_Types.lhs" class="cut">02_Hard_Part/<strong>22_Types.lhs</strong></a></p>
<p>But it doesnt protect you much. Try to swap the two parameter of <code>showInfos</code> and run the program:</p>
<div class="sourceCode" id="cb83"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb83-1" title="1"> <span class="fu">putStrLn</span> <span class="op">$</span> showInfos color name</a></code></pre></div>
<p>It will compile and execute. In fact you can replace Name, Color and String everywhere. The compiler will treat them as completely identical.</p>
<p>Another method is to create your own types using the keyword <code>data</code>.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb84"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb84-1" title="1"><span class="kw">data</span> <span class="dt">Name</span> <span class="ot">=</span> <span class="dt">NameConstr</span> <span class="dt">String</span></a>
<a class="sourceLine" id="cb84-2" title="2"><span class="kw">data</span> <span class="dt">Color</span> <span class="ot">=</span> <span class="dt">ColorConstr</span> <span class="dt">String</span></a>
<a class="sourceLine" id="cb84-3" title="3"></a>
<a class="sourceLine" id="cb84-4" title="4"><span class="ot">showInfos ::</span> <span class="dt">Name</span> <span class="ot">-&gt;</span> <span class="dt">Color</span> <span class="ot">-&gt;</span> <span class="dt">String</span></a>
<a class="sourceLine" id="cb84-5" title="5">showInfos (<span class="dt">NameConstr</span> name) (<span class="dt">ColorConstr</span> color) <span class="ot">=</span></a>
<a class="sourceLine" id="cb84-6" title="6"> <span class="st">&quot;Name: &quot;</span> <span class="op">++</span> name <span class="op">++</span> <span class="st">&quot;, Color: &quot;</span> <span class="op">++</span> color</a>
<a class="sourceLine" id="cb84-7" title="7"></a>
<a class="sourceLine" id="cb84-8" title="8">name <span class="ot">=</span> <span class="dt">NameConstr</span> <span class="st">&quot;Robin&quot;</span></a>
<a class="sourceLine" id="cb84-9" title="9">color <span class="ot">=</span> <span class="dt">ColorConstr</span> <span class="st">&quot;Blue&quot;</span></a>
<a class="sourceLine" id="cb84-10" title="10">main <span class="ot">=</span> <span class="fu">putStrLn</span> <span class="op">$</span> showInfos name color</a></code></pre></div>
</div>
<p>Now if you switch parameters of <code>showInfos</code>, the compiler complains! So this is a potential mistake you will never make again and the only price is to be more verbose.</p>
<p>Also notice that constructors are functions:</p>
<div class="sourceCode" id="cb85"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb85-1" title="1"><span class="dt">NameConstr</span><span class="ot"> ::</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">Name</span></a>
<a class="sourceLine" id="cb85-2" title="2"><span class="dt">ColorConstr</span><span class="ot"> ::</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">Color</span></a></code></pre></div>
<p>The syntax of <code>data</code> is mainly:</p>
<div class="sourceCode" id="cb86"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb86-1" title="1"><span class="kw">data</span> <span class="dt">TypeName</span> <span class="ot">=</span> <span class="dt">ConstructorName</span> [types]</a>
<a class="sourceLine" id="cb86-2" title="2"> <span class="op">|</span> <span class="dt">ConstructorName2</span> [types]</a>
<a class="sourceLine" id="cb86-3" title="3"> <span class="op">|</span> <span class="op">...</span></a></code></pre></div>
<p>Generally the usage is to use the same name for the DataTypeName and DataTypeConstructor.</p>
<p>Example:</p>
<div class="sourceCode" id="cb87"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb87-1" title="1"><span class="kw">data</span> <span class="dt">Complex</span> a <span class="ot">=</span> <span class="dt">Num</span> a <span class="ot">=&gt;</span> <span class="dt">Complex</span> a a</a></code></pre></div>
<p>Also you can use the record syntax:</p>
<div class="sourceCode" id="cb88"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb88-1" title="1"><span class="kw">data</span> <span class="dt">DataTypeName</span> <span class="ot">=</span> <span class="dt">DataConstructor</span> {</a>
<a class="sourceLine" id="cb88-2" title="2"><span class="ot"> field1 ::</span> [<span class="kw">type</span> <span class="kw">of</span> field1]</a>
<a class="sourceLine" id="cb88-3" title="3"> ,<span class="ot"> field2 ::</span> [<span class="kw">type</span> <span class="kw">of</span> field2]</a>
<a class="sourceLine" id="cb88-4" title="4"> <span class="op">...</span></a>
<a class="sourceLine" id="cb88-5" title="5"> ,<span class="ot"> fieldn ::</span> [<span class="kw">type</span> <span class="kw">of</span> fieldn] }</a></code></pre></div>
<p>And many accessors are made for you. Furthermore you can use another order when setting values.</p>
<p>Example:</p>
<div class="sourceCode" id="cb89"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb89-1" title="1"><span class="kw">data</span> <span class="dt">Complex</span> a <span class="ot">=</span> <span class="dt">Num</span> a <span class="ot">=&gt;</span> <span class="dt">Complex</span> {<span class="ot"> real ::</span> a,<span class="ot"> img ::</span> a}</a>
<a class="sourceLine" id="cb89-2" title="2">c <span class="ot">=</span> <span class="dt">Complex</span> <span class="fl">1.0</span> <span class="fl">2.0</span></a>
<a class="sourceLine" id="cb89-3" title="3">z <span class="ot">=</span> <span class="dt">Complex</span> { real <span class="ot">=</span> <span class="dv">3</span>, img <span class="ot">=</span> <span class="dv">4</span> }</a>
<a class="sourceLine" id="cb89-4" title="4">real c <span class="ot"></span> <span class="fl">1.0</span></a>
<a class="sourceLine" id="cb89-5" title="5">img z <span class="ot"></span> <span class="dv">4</span></a></code></pre></div>
<p><a href="code/02_Hard_Part/22_Types.lhs" class="cut">02_Hard_Part/<strong>22_Types.lhs</strong> </a></p>
<hr />
<p><a href="code/02_Hard_Part/23_Types.lhs" class="cut">02_Hard_Part/<strong>23_Types.lhs</strong></a></p>
<h4 id="recursive-type">
Recursive type
</h4>
<p>You already encountered a recursive type: lists. You can re-create lists, but with a more verbose syntax:</p>
<div class="sourceCode" id="cb90"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb90-1" title="1"><span class="kw">data</span> <span class="dt">List</span> a <span class="ot">=</span> <span class="dt">Empty</span> <span class="op">|</span> <span class="dt">Cons</span> a (<span class="dt">List</span> a)</a></code></pre></div>
<p>If you really want to use an easier syntax you can use an infix name for constructors.</p>
<div class="sourceCode" id="cb91"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb91-1" title="1"><span class="kw">infixr</span> <span class="dv">5</span> <span class="op">:::</span></a>
<a class="sourceLine" id="cb91-2" title="2"><span class="kw">data</span> <span class="dt">List</span> a <span class="ot">=</span> <span class="dt">Nil</span> <span class="op">|</span> a <span class="op">:::</span> (<span class="dt">List</span> a)</a></code></pre></div>
<p>The number after <code>infixr</code> gives the precedence.</p>
<p>If you want to be able to print (<code>Show</code>), read (<code>Read</code>), test equality (<code>Eq</code>) and compare (<code>Ord</code>) your new data structure you can tell Haskell to derive the appropriate functions for you.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb92"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb92-1" title="1"><span class="kw">infixr</span> <span class="dv">5</span> <span class="op">:::</span></a>
<a class="sourceLine" id="cb92-2" title="2"><span class="kw">data</span> <span class="dt">List</span> a <span class="ot">=</span> <span class="dt">Nil</span> <span class="op">|</span> a <span class="op">:::</span> (<span class="dt">List</span> a)</a>
<a class="sourceLine" id="cb92-3" title="3"> <span class="kw">deriving</span> (<span class="dt">Show</span>,<span class="dt">Read</span>,<span class="dt">Eq</span>,<span class="dt">Ord</span>)</a></code></pre></div>
</div>
<p>When you add <code>deriving (Show)</code> to your data declaration, Haskell creates a <code>show</code> function for you. Well see soon how you can use your own <code>show</code> function.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb93"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb93-1" title="1">convertList [] <span class="ot">=</span> <span class="dt">Nil</span></a>
<a class="sourceLine" id="cb93-2" title="2">convertList (x<span class="op">:</span>xs) <span class="ot">=</span> x <span class="op">:::</span> convertList xs</a></code></pre></div>
</div>
<div class="codehighlight">
<div class="sourceCode" id="cb94"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb94-1" title="1">main <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb94-2" title="2"> <span class="fu">print</span> (<span class="dv">0</span> <span class="op">:::</span> <span class="dv">1</span> <span class="op">:::</span> <span class="dt">Nil</span>)</a>
<a class="sourceLine" id="cb94-3" title="3"> <span class="fu">print</span> (convertList [<span class="dv">0</span>,<span class="dv">1</span>])</a></code></pre></div>
</div>
<p>This prints:</p>
<pre><code>0 ::: (1 ::: Nil)
0 ::: (1 ::: Nil)</code></pre>
<p><a href="code/02_Hard_Part/23_Types.lhs" class="cut">02_Hard_Part/<strong>23_Types.lhs</strong> </a></p>
<hr />
<p><a href="code/02_Hard_Part/30_Trees.lhs" class="cut">02_Hard_Part/<strong>30_Trees.lhs</strong></a></p>
<h4 id="trees">
Trees
</h4>
<div>
<img src="../../../../Scratch/img/blog/Haskell-the-Hard-Way/magritte-l-arbre.jpg" alt="Magritte, l" />
</div>
<p>Well just give another standard example: binary trees.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb96"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb96-1" title="1"><span class="kw">import</span> <span class="dt">Data.List</span></a>
<a class="sourceLine" id="cb96-2" title="2"></a>
<a class="sourceLine" id="cb96-3" title="3"><span class="kw">data</span> <span class="dt">BinTree</span> a <span class="ot">=</span> <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb96-4" title="4"> <span class="op">|</span> <span class="dt">Node</span> a (<span class="dt">BinTree</span> a) (<span class="dt">BinTree</span> a)</a>
<a class="sourceLine" id="cb96-5" title="5"> <span class="kw">deriving</span> (<span class="dt">Show</span>)</a></code></pre></div>
</div>
<p>We will also create a function which turns a list into an ordered binary tree.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb97"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb97-1" title="1"><span class="ot">treeFromList ::</span> (<span class="dt">Ord</span> a) <span class="ot">=&gt;</span> [a] <span class="ot">-&gt;</span> <span class="dt">BinTree</span> a</a>
<a class="sourceLine" id="cb97-2" title="2">treeFromList [] <span class="ot">=</span> <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb97-3" title="3">treeFromList (x<span class="op">:</span>xs) <span class="ot">=</span> <span class="dt">Node</span> x (treeFromList (<span class="fu">filter</span> (<span class="op">&lt;</span>x) xs))</a>
<a class="sourceLine" id="cb97-4" title="4"> (treeFromList (<span class="fu">filter</span> (<span class="op">&gt;</span>x) xs))</a></code></pre></div>
</div>
<p>Look at how elegant this function is. In plain English:</p>
<ul>
<li>an empty list will be converted to an empty tree.</li>
<li>a list <code>(x:xs)</code> will be converted to a tree where:
<ul>
<li>The root is <code>x</code></li>
<li>Its left subtree is the tree created from members of the list <code>xs</code> which are strictly inferior to <code>x</code> and</li>
<li>the right subtree is the tree created from members of the list <code>xs</code> which are strictly superior to <code>x</code>.</li>
</ul></li>
</ul>
<div class="codehighlight">
<div class="sourceCode" id="cb98"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb98-1" title="1">main <span class="ot">=</span> <span class="fu">print</span> <span class="op">$</span> treeFromList [<span class="dv">7</span>,<span class="dv">2</span>,<span class="dv">4</span>,<span class="dv">8</span>]</a></code></pre></div>
</div>
<p>You should obtain the following:</p>
<pre><code>Node 7 (Node 2 Empty (Node 4 Empty Empty)) (Node 8 Empty Empty)</code></pre>
<p>This is an informative but quite unpleasant representation of our tree.</p>
<p><a href="code/02_Hard_Part/30_Trees.lhs" class="cut">02_Hard_Part/<strong>30_Trees.lhs</strong> </a></p>
<hr />
<p><a href="code/02_Hard_Part/31_Trees.lhs" class="cut">02_Hard_Part/<strong>31_Trees.lhs</strong></a></p>
<p>Just for fun, lets code a better display for our trees. I simply had fun making a nice function to display trees in a general way. You can safely skip this part if you find it too difficult to follow.</p>
<p>We have a few changes to make. We remove the <code>deriving (Show)</code> from the declaration of our <code>BinTree</code> type. And it might also be useful to make our BinTree an instance of (<code>Eq</code> and <code>Ord</code>) so we will be able to test equality and compare trees.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb100"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb100-1" title="1"><span class="kw">data</span> <span class="dt">BinTree</span> a <span class="ot">=</span> <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb100-2" title="2"> <span class="op">|</span> <span class="dt">Node</span> a (<span class="dt">BinTree</span> a) (<span class="dt">BinTree</span> a)</a>
<a class="sourceLine" id="cb100-3" title="3"> <span class="kw">deriving</span> (<span class="dt">Eq</span>,<span class="dt">Ord</span>)</a></code></pre></div>
</div>
<p>Without the <code>deriving (Show)</code>, Haskell doesnt create a <code>show</code> method for us. We will create our own version of <code>show</code>. To achieve this, we must declare that our newly created type <code>BinTree a</code> is an instance of the type class <code>Show</code>. The general syntax is:</p>
<div class="sourceCode" id="cb101"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb101-1" title="1"><span class="kw">instance</span> <span class="dt">Show</span> (<span class="dt">BinTree</span> a) <span class="kw">where</span></a>
<a class="sourceLine" id="cb101-2" title="2"> <span class="fu">show</span> t <span class="ot">=</span> <span class="op">...</span> <span class="co">-- You declare your function here</span></a></code></pre></div>
<p>Here is my version of how to show a binary tree. Dont worry about the apparent complexity. I made a lot of improvements in order to display even stranger objects.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb102"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb102-1" title="1"><span class="co">-- declare BinTree a to be an instance of Show</span></a>
<a class="sourceLine" id="cb102-2" title="2"><span class="kw">instance</span> (<span class="dt">Show</span> a) <span class="ot">=&gt;</span> <span class="dt">Show</span> (<span class="dt">BinTree</span> a) <span class="kw">where</span></a>
<a class="sourceLine" id="cb102-3" title="3"> <span class="co">-- will start by a '&lt;' before the root</span></a>
<a class="sourceLine" id="cb102-4" title="4"> <span class="co">-- and put a : a begining of line</span></a>
<a class="sourceLine" id="cb102-5" title="5"> <span class="fu">show</span> t <span class="ot">=</span> <span class="st">&quot;&lt; &quot;</span> <span class="op">++</span> replace <span class="ch">'\n'</span> <span class="st">&quot;\n: &quot;</span> (treeshow <span class="st">&quot;&quot;</span> t)</a>
<a class="sourceLine" id="cb102-6" title="6"> <span class="kw">where</span></a>
<a class="sourceLine" id="cb102-7" title="7"> <span class="co">-- treeshow pref Tree</span></a>
<a class="sourceLine" id="cb102-8" title="8"> <span class="co">-- shows a tree and starts each line with pref</span></a>
<a class="sourceLine" id="cb102-9" title="9"> <span class="co">-- We don't display the Empty tree</span></a>
<a class="sourceLine" id="cb102-10" title="10"> treeshow pref <span class="dt">Empty</span> <span class="ot">=</span> <span class="st">&quot;&quot;</span></a>
<a class="sourceLine" id="cb102-11" title="11"> <span class="co">-- Leaf</span></a>
<a class="sourceLine" id="cb102-12" title="12"> treeshow pref (<span class="dt">Node</span> x <span class="dt">Empty</span> <span class="dt">Empty</span>) <span class="ot">=</span></a>
<a class="sourceLine" id="cb102-13" title="13"> (pshow pref x)</a>
<a class="sourceLine" id="cb102-14" title="14"></a>
<a class="sourceLine" id="cb102-15" title="15"> <span class="co">-- Right branch is empty</span></a>
<a class="sourceLine" id="cb102-16" title="16"> treeshow pref (<span class="dt">Node</span> x left <span class="dt">Empty</span>) <span class="ot">=</span></a>
<a class="sourceLine" id="cb102-17" title="17"> (pshow pref x) <span class="op">++</span> <span class="st">&quot;\n&quot;</span> <span class="op">++</span></a>
<a class="sourceLine" id="cb102-18" title="18"> (showSon pref <span class="st">&quot;`--&quot;</span> <span class="st">&quot; &quot;</span> left)</a>
<a class="sourceLine" id="cb102-19" title="19"></a>
<a class="sourceLine" id="cb102-20" title="20"> <span class="co">-- Left branch is empty</span></a>
<a class="sourceLine" id="cb102-21" title="21"> treeshow pref (<span class="dt">Node</span> x <span class="dt">Empty</span> right) <span class="ot">=</span></a>
<a class="sourceLine" id="cb102-22" title="22"> (pshow pref x) <span class="op">++</span> <span class="st">&quot;\n&quot;</span> <span class="op">++</span></a>
<a class="sourceLine" id="cb102-23" title="23"> (showSon pref <span class="st">&quot;`--&quot;</span> <span class="st">&quot; &quot;</span> right)</a>
<a class="sourceLine" id="cb102-24" title="24"></a>
<a class="sourceLine" id="cb102-25" title="25"> <span class="co">-- Tree with left and right children non empty</span></a>
<a class="sourceLine" id="cb102-26" title="26"> treeshow pref (<span class="dt">Node</span> x left right) <span class="ot">=</span></a>
<a class="sourceLine" id="cb102-27" title="27"> (pshow pref x) <span class="op">++</span> <span class="st">&quot;\n&quot;</span> <span class="op">++</span></a>
<a class="sourceLine" id="cb102-28" title="28"> (showSon pref <span class="st">&quot;|--&quot;</span> <span class="st">&quot;| &quot;</span> left) <span class="op">++</span> <span class="st">&quot;\n&quot;</span> <span class="op">++</span></a>
<a class="sourceLine" id="cb102-29" title="29"> (showSon pref <span class="st">&quot;`--&quot;</span> <span class="st">&quot; &quot;</span> right)</a>
<a class="sourceLine" id="cb102-30" title="30"></a>
<a class="sourceLine" id="cb102-31" title="31"> <span class="co">-- shows a tree using some prefixes to make it nice</span></a>
<a class="sourceLine" id="cb102-32" title="32"> showSon pref before next t <span class="ot">=</span></a>
<a class="sourceLine" id="cb102-33" title="33"> pref <span class="op">++</span> before <span class="op">++</span> treeshow (pref <span class="op">++</span> next) t</a>
<a class="sourceLine" id="cb102-34" title="34"></a>
<a class="sourceLine" id="cb102-35" title="35"> <span class="co">-- pshow replaces &quot;\n&quot; by &quot;\n&quot;++pref</span></a>
<a class="sourceLine" id="cb102-36" title="36"> pshow pref x <span class="ot">=</span> replace <span class="ch">'\n'</span> (<span class="st">&quot;\n&quot;</span><span class="op">++</span>pref) (<span class="fu">show</span> x)</a>
<a class="sourceLine" id="cb102-37" title="37"></a>
<a class="sourceLine" id="cb102-38" title="38"> <span class="co">-- replaces one char by another string</span></a>
<a class="sourceLine" id="cb102-39" title="39"> replace c new string <span class="ot">=</span></a>
<a class="sourceLine" id="cb102-40" title="40"> <span class="fu">concatMap</span> (change c new) string</a>
<a class="sourceLine" id="cb102-41" title="41"> <span class="kw">where</span></a>
<a class="sourceLine" id="cb102-42" title="42"> change c new x</a>
<a class="sourceLine" id="cb102-43" title="43"> <span class="op">|</span> x <span class="op">==</span> c <span class="ot">=</span> new</a>
<a class="sourceLine" id="cb102-44" title="44"> <span class="op">|</span> <span class="fu">otherwise</span> <span class="ot">=</span> x<span class="op">:</span>[] <span class="co">-- &quot;x&quot;</span></a></code></pre></div>
</div>
<p>The <code>treeFromList</code> method remains identical.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb103"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb103-1" title="1"><span class="ot">treeFromList ::</span> (<span class="dt">Ord</span> a) <span class="ot">=&gt;</span> [a] <span class="ot">-&gt;</span> <span class="dt">BinTree</span> a</a>
<a class="sourceLine" id="cb103-2" title="2">treeFromList [] <span class="ot">=</span> <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb103-3" title="3">treeFromList (x<span class="op">:</span>xs) <span class="ot">=</span> <span class="dt">Node</span> x (treeFromList (<span class="fu">filter</span> (<span class="op">&lt;</span>x) xs))</a>
<a class="sourceLine" id="cb103-4" title="4"> (treeFromList (<span class="fu">filter</span> (<span class="op">&gt;</span>x) xs))</a></code></pre></div>
</div>
<p>And now, we can play:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb104"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb104-1" title="1">main <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb104-2" title="2"> <span class="fu">putStrLn</span> <span class="st">&quot;Int binary tree:&quot;</span></a>
<a class="sourceLine" id="cb104-3" title="3"> <span class="fu">print</span> <span class="op">$</span> treeFromList [<span class="dv">7</span>,<span class="dv">2</span>,<span class="dv">4</span>,<span class="dv">8</span>,<span class="dv">1</span>,<span class="dv">3</span>,<span class="dv">6</span>,<span class="dv">21</span>,<span class="dv">12</span>,<span class="dv">23</span>]</a></code></pre></div>
</div>
<pre><code>Int binary tree:
&lt; 7
: |--2
: | |--1
: | `--4
: | |--3
: | `--6
: `--8
: `--21
: |--12
: `--23</code></pre>
<p>Now it is far better! The root is shown by starting the line with the <code>&lt;</code> character. And each following line starts with a <code>:</code>. But we could also use another type.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb106"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb106-1" title="1"> <span class="fu">putStrLn</span> <span class="st">&quot;\nString binary tree:&quot;</span></a>
<a class="sourceLine" id="cb106-2" title="2"> <span class="fu">print</span> <span class="op">$</span> treeFromList [<span class="st">&quot;foo&quot;</span>,<span class="st">&quot;bar&quot;</span>,<span class="st">&quot;baz&quot;</span>,<span class="st">&quot;gor&quot;</span>,<span class="st">&quot;yog&quot;</span>]</a></code></pre></div>
</div>
<pre><code>String binary tree:
&lt; &quot;foo&quot;
: |--&quot;bar&quot;
: | `--&quot;baz&quot;
: `--&quot;gor&quot;
: `--&quot;yog&quot;</code></pre>
<p>As we can test equality and order trees, we can make tree of trees!</p>
<div class="codehighlight">
<div class="sourceCode" id="cb108"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb108-1" title="1"> <span class="fu">putStrLn</span> <span class="st">&quot;\nBinary tree of Char binary trees:&quot;</span></a>
<a class="sourceLine" id="cb108-2" title="2"> <span class="fu">print</span> ( treeFromList</a>
<a class="sourceLine" id="cb108-3" title="3"> (<span class="fu">map</span> treeFromList [<span class="st">&quot;baz&quot;</span>,<span class="st">&quot;zara&quot;</span>,<span class="st">&quot;bar&quot;</span>]))</a></code></pre></div>
</div>
<pre><code>Binary tree of Char binary trees:
&lt; &lt; 'b'
: : |--'a'
: : `--'z'
: |--&lt; 'b'
: | : |--'a'
: | : `--'r'
: `--&lt; 'z'
: : `--'a'
: : `--'r'</code></pre>
<p>This is why I chose to prefix each line of tree display by <code>:</code> (except for the root).</p>
<div>
<img src="../../../../Scratch/img/blog/Haskell-the-Hard-Way/yo_dawg_tree.jpg" alt="Yo Dawg Tree" />
</div>
<div class="codehighlight">
<div class="sourceCode" id="cb110"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb110-1" title="1"> <span class="fu">putStrLn</span> <span class="st">&quot;\nTree of Binary trees of Char binary trees:&quot;</span></a>
<a class="sourceLine" id="cb110-2" title="2"> <span class="fu">print</span> <span class="op">$</span> (treeFromList <span class="op">.</span> <span class="fu">map</span> (treeFromList <span class="op">.</span> <span class="fu">map</span> treeFromList))</a>
<a class="sourceLine" id="cb110-3" title="3"> [ [<span class="st">&quot;YO&quot;</span>,<span class="st">&quot;DAWG&quot;</span>]</a>
<a class="sourceLine" id="cb110-4" title="4"> , [<span class="st">&quot;I&quot;</span>,<span class="st">&quot;HEARD&quot;</span>]</a>
<a class="sourceLine" id="cb110-5" title="5"> , [<span class="st">&quot;I&quot;</span>,<span class="st">&quot;HEARD&quot;</span>]</a>
<a class="sourceLine" id="cb110-6" title="6"> , [<span class="st">&quot;YOU&quot;</span>,<span class="st">&quot;LIKE&quot;</span>,<span class="st">&quot;TREES&quot;</span>] ]</a></code></pre></div>
</div>
<p>Which is equivalent to</p>
<div class="sourceCode" id="cb111"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb111-1" title="1"><span class="fu">print</span> ( treeFromList (</a>
<a class="sourceLine" id="cb111-2" title="2"> <span class="fu">map</span> treeFromList</a>
<a class="sourceLine" id="cb111-3" title="3"> [ <span class="fu">map</span> treeFromList [<span class="st">&quot;YO&quot;</span>,<span class="st">&quot;DAWG&quot;</span>]</a>
<a class="sourceLine" id="cb111-4" title="4"> , <span class="fu">map</span> treeFromList [<span class="st">&quot;I&quot;</span>,<span class="st">&quot;HEARD&quot;</span>]</a>
<a class="sourceLine" id="cb111-5" title="5"> , <span class="fu">map</span> treeFromList [<span class="st">&quot;I&quot;</span>,<span class="st">&quot;HEARD&quot;</span>]</a>
<a class="sourceLine" id="cb111-6" title="6"> , <span class="fu">map</span> treeFromList [<span class="st">&quot;YOU&quot;</span>,<span class="st">&quot;LIKE&quot;</span>,<span class="st">&quot;TREES&quot;</span>] ]))</a></code></pre></div>
<p>and gives:</p>
<pre><code>Binary tree of Binary trees of Char binary trees:
&lt; &lt; &lt; 'Y'
: : : `--'O'
: : `--&lt; 'D'
: : : |--'A'
: : : `--'W'
: : : `--'G'
: |--&lt; &lt; 'I'
: | : `--&lt; 'H'
: | : : |--'E'
: | : : | `--'A'
: | : : | `--'D'
: | : : `--'R'
: `--&lt; &lt; 'Y'
: : : `--'O'
: : : `--'U'
: : `--&lt; 'L'
: : : `--'I'
: : : |--'E'
: : : `--'K'
: : `--&lt; 'T'
: : : `--'R'
: : : |--'E'
: : : `--'S'</code></pre>
<p>Notice how duplicate trees arent inserted; there is only one tree corresponding to <code>"I","HEARD"</code>. We have this for (almost) free, because we have declared Tree to be an instance of <code>Eq</code>.</p>
<p>See how awesome this structure is: We can make trees containing not only integers, strings and chars, but also other trees. And we can even make a tree containing a tree of trees!</p>
<p><a href="code/02_Hard_Part/31_Trees.lhs" class="cut">02_Hard_Part/<strong>31_Trees.lhs</strong> </a></p>
<hr />
<p><a href="code/02_Hard_Part/40_Infinites_Structures.lhs" class="cut">02_Hard_Part/<strong>40_Infinites_Structures.lhs</strong></a></p>
<h3 id="infinite-structures">
Infinite Structures
</h3>
<div>
<img src="../../../../Scratch/img/blog/Haskell-the-Hard-Way/escher_infinite_lizards.jpg" alt="Escher" />
</div>
<p>It is often said that Haskell is <em>lazy</em>.</p>
<p>In fact, if you are a bit pedantic, you should say that <a href="http://www.haskell.org/haskellwiki/Lazy_vs._non-strict">Haskell is <em>non-strict</em></a>. Laziness is just a common implementation for non-strict languages.</p>
<p>Then what does “not-strict” mean? From the Haskell wiki:</p>
<blockquote>
<p>Reduction (the mathematical term for evaluation) proceeds from the outside in.</p>
<p>so if you have <code>(a+(b*c))</code> then you first reduce <code>+</code> first, then you reduce the inner <code>(b*c)</code></p>
</blockquote>
<p>For example in Haskell you can do:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb113"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb113-1" title="1"><span class="co">-- numbers = [1,2,..]</span></a>
<a class="sourceLine" id="cb113-2" title="2"><span class="ot">numbers ::</span> [<span class="dt">Integer</span>]</a>
<a class="sourceLine" id="cb113-3" title="3">numbers <span class="ot">=</span> <span class="dv">0</span><span class="op">:</span><span class="fu">map</span> (<span class="dv">1</span><span class="op">+</span>) numbers</a>
<a class="sourceLine" id="cb113-4" title="4"></a>
<a class="sourceLine" id="cb113-5" title="5">take' n [] <span class="ot">=</span> []</a>
<a class="sourceLine" id="cb113-6" title="6">take' <span class="dv">0</span> l <span class="ot">=</span> []</a>
<a class="sourceLine" id="cb113-7" title="7">take' n (x<span class="op">:</span>xs) <span class="ot">=</span> x<span class="op">:</span>take' (n<span class="op">-</span><span class="dv">1</span>) xs</a>
<a class="sourceLine" id="cb113-8" title="8"></a>
<a class="sourceLine" id="cb113-9" title="9">main <span class="ot">=</span> <span class="fu">print</span> <span class="op">$</span> take' <span class="dv">10</span> numbers</a></code></pre></div>
</div>
<p>And it stops.</p>
<p>How?</p>
<p>Instead of trying to evaluate <code>numbers</code> entirely, it evaluates elements only when needed.</p>
<p>Also, note in Haskell there is a notation for infinite lists</p>
<pre><code>[1..] ⇔ [1,2,3,4...]
[1,3..] ⇔ [1,3,5,7,9,11...]</code></pre>
<p>and most functions will work with them. Also, there is a built-in function <code>take</code> which is equivalent to our <code>take'</code>.</p>
<p><a href="code/02_Hard_Part/40_Infinites_Structures.lhs" class="cut">02_Hard_Part/<strong>40_Infinites_Structures.lhs</strong> </a></p>
<hr />
<p><a href="code/02_Hard_Part/41_Infinites_Structures.lhs" class="cut">02_Hard_Part/<strong>41_Infinites_Structures.lhs</strong></a></p>
<div style="display:none">
<p>This code is mostly the same as the previous one.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb115"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb115-1" title="1"><span class="kw">import</span> <span class="dt">Debug.Trace</span> (trace)</a>
<a class="sourceLine" id="cb115-2" title="2"><span class="kw">import</span> <span class="dt">Data.List</span></a>
<a class="sourceLine" id="cb115-3" title="3"><span class="kw">data</span> <span class="dt">BinTree</span> a <span class="ot">=</span> <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb115-4" title="4"> <span class="op">|</span> <span class="dt">Node</span> a (<span class="dt">BinTree</span> a) (<span class="dt">BinTree</span> a)</a>
<a class="sourceLine" id="cb115-5" title="5"> <span class="kw">deriving</span> (<span class="dt">Eq</span>,<span class="dt">Ord</span>)</a></code></pre></div>
</div>
<div class="codehighlight">
<div class="sourceCode" id="cb116"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb116-1" title="1"><span class="co">-- declare BinTree a to be an instance of Show</span></a>
<a class="sourceLine" id="cb116-2" title="2"><span class="kw">instance</span> (<span class="dt">Show</span> a) <span class="ot">=&gt;</span> <span class="dt">Show</span> (<span class="dt">BinTree</span> a) <span class="kw">where</span></a>
<a class="sourceLine" id="cb116-3" title="3"> <span class="co">-- will start by a '&lt;' before the root</span></a>
<a class="sourceLine" id="cb116-4" title="4"> <span class="co">-- and put a : a begining of line</span></a>
<a class="sourceLine" id="cb116-5" title="5"> <span class="fu">show</span> t <span class="ot">=</span> <span class="st">&quot;&lt; &quot;</span> <span class="op">++</span> replace <span class="ch">'\n'</span> <span class="st">&quot;\n: &quot;</span> (treeshow <span class="st">&quot;&quot;</span> t)</a>
<a class="sourceLine" id="cb116-6" title="6"> <span class="kw">where</span></a>
<a class="sourceLine" id="cb116-7" title="7"> treeshow pref <span class="dt">Empty</span> <span class="ot">=</span> <span class="st">&quot;&quot;</span></a>
<a class="sourceLine" id="cb116-8" title="8"> treeshow pref (<span class="dt">Node</span> x <span class="dt">Empty</span> <span class="dt">Empty</span>) <span class="ot">=</span></a>
<a class="sourceLine" id="cb116-9" title="9"> (pshow pref x)</a>
<a class="sourceLine" id="cb116-10" title="10"></a>
<a class="sourceLine" id="cb116-11" title="11"> treeshow pref (<span class="dt">Node</span> x left <span class="dt">Empty</span>) <span class="ot">=</span></a>
<a class="sourceLine" id="cb116-12" title="12"> (pshow pref x) <span class="op">++</span> <span class="st">&quot;\n&quot;</span> <span class="op">++</span></a>
<a class="sourceLine" id="cb116-13" title="13"> (showSon pref <span class="st">&quot;`--&quot;</span> <span class="st">&quot; &quot;</span> left)</a>
<a class="sourceLine" id="cb116-14" title="14"></a>
<a class="sourceLine" id="cb116-15" title="15"> treeshow pref (<span class="dt">Node</span> x <span class="dt">Empty</span> right) <span class="ot">=</span></a>
<a class="sourceLine" id="cb116-16" title="16"> (pshow pref x) <span class="op">++</span> <span class="st">&quot;\n&quot;</span> <span class="op">++</span></a>
<a class="sourceLine" id="cb116-17" title="17"> (showSon pref <span class="st">&quot;`--&quot;</span> <span class="st">&quot; &quot;</span> right)</a>
<a class="sourceLine" id="cb116-18" title="18"></a>
<a class="sourceLine" id="cb116-19" title="19"> treeshow pref (<span class="dt">Node</span> x left right) <span class="ot">=</span></a>
<a class="sourceLine" id="cb116-20" title="20"> (pshow pref x) <span class="op">++</span> <span class="st">&quot;\n&quot;</span> <span class="op">++</span></a>
<a class="sourceLine" id="cb116-21" title="21"> (showSon pref <span class="st">&quot;|--&quot;</span> <span class="st">&quot;| &quot;</span> left) <span class="op">++</span> <span class="st">&quot;\n&quot;</span> <span class="op">++</span></a>
<a class="sourceLine" id="cb116-22" title="22"> (showSon pref <span class="st">&quot;`--&quot;</span> <span class="st">&quot; &quot;</span> right)</a>
<a class="sourceLine" id="cb116-23" title="23"></a>
<a class="sourceLine" id="cb116-24" title="24"> <span class="co">-- show a tree using some prefixes to make it nice</span></a>
<a class="sourceLine" id="cb116-25" title="25"> showSon pref before next t <span class="ot">=</span></a>
<a class="sourceLine" id="cb116-26" title="26"> pref <span class="op">++</span> before <span class="op">++</span> treeshow (pref <span class="op">++</span> next) t</a>
<a class="sourceLine" id="cb116-27" title="27"></a>
<a class="sourceLine" id="cb116-28" title="28"> <span class="co">-- pshow replace &quot;\n&quot; by &quot;\n&quot;++pref</span></a>
<a class="sourceLine" id="cb116-29" title="29"> pshow pref x <span class="ot">=</span> replace <span class="ch">'\n'</span> (<span class="st">&quot;\n&quot;</span><span class="op">++</span>pref) (<span class="st">&quot; &quot;</span> <span class="op">++</span> <span class="fu">show</span> x)</a>
<a class="sourceLine" id="cb116-30" title="30"></a>
<a class="sourceLine" id="cb116-31" title="31"> <span class="co">-- replace on char by another string</span></a>
<a class="sourceLine" id="cb116-32" title="32"> replace c new string <span class="ot">=</span></a>
<a class="sourceLine" id="cb116-33" title="33"> <span class="fu">concatMap</span> (change c new) string</a>
<a class="sourceLine" id="cb116-34" title="34"> <span class="kw">where</span></a>
<a class="sourceLine" id="cb116-35" title="35"> change c new x</a>
<a class="sourceLine" id="cb116-36" title="36"> <span class="op">|</span> x <span class="op">==</span> c <span class="ot">=</span> new</a>
<a class="sourceLine" id="cb116-37" title="37"> <span class="op">|</span> <span class="fu">otherwise</span> <span class="ot">=</span> x<span class="op">:</span>[] <span class="co">-- &quot;x&quot;</span></a></code></pre></div>
</div>
</div>
<p>Suppose we dont mind having an ordered binary tree. Here is an infinite binary tree:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb117"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb117-1" title="1">nullTree <span class="ot">=</span> <span class="dt">Node</span> <span class="dv">0</span> nullTree nullTree</a></code></pre></div>
</div>
<p>A complete binary tree where each node is equal to 0. Now I will prove you can manipulate this object using the following function:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb118"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb118-1" title="1"><span class="co">-- take all element of a BinTree</span></a>
<a class="sourceLine" id="cb118-2" title="2"><span class="co">-- up to some depth</span></a>
<a class="sourceLine" id="cb118-3" title="3">treeTakeDepth _ <span class="dt">Empty</span> <span class="ot">=</span> <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb118-4" title="4">treeTakeDepth <span class="dv">0</span> _ <span class="ot">=</span> <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb118-5" title="5">treeTakeDepth n (<span class="dt">Node</span> x left right) <span class="ot">=</span> <span class="kw">let</span></a>
<a class="sourceLine" id="cb118-6" title="6"> nl <span class="ot">=</span> treeTakeDepth (n<span class="op">-</span><span class="dv">1</span>) left</a>
<a class="sourceLine" id="cb118-7" title="7"> nr <span class="ot">=</span> treeTakeDepth (n<span class="op">-</span><span class="dv">1</span>) right</a>
<a class="sourceLine" id="cb118-8" title="8"> <span class="kw">in</span></a>
<a class="sourceLine" id="cb118-9" title="9"> <span class="dt">Node</span> x nl nr</a></code></pre></div>
</div>
<p>See what occurs for this program:</p>
<div class="sourceCode" id="cb119"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb119-1" title="1">main <span class="ot">=</span> <span class="fu">print</span> <span class="op">$</span> treeTakeDepth <span class="dv">4</span> nullTree</a></code></pre></div>
<p>This code compiles, runs and stops giving the following result:</p>
<pre><code>&lt; 0
: |-- 0
: | |-- 0
: | | |-- 0
: | | `-- 0
: | `-- 0
: | |-- 0
: | `-- 0
: `-- 0
: |-- 0
: | |-- 0
: | `-- 0
: `-- 0
: |-- 0
: `-- 0</code></pre>
<p>Just to heat up your neurones a bit more, lets make a slightly more interesting tree:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb121"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb121-1" title="1">iTree <span class="ot">=</span> <span class="dt">Node</span> <span class="dv">0</span> (dec iTree) (inc iTree)</a>
<a class="sourceLine" id="cb121-2" title="2"> <span class="kw">where</span></a>
<a class="sourceLine" id="cb121-3" title="3"> dec (<span class="dt">Node</span> x l r) <span class="ot">=</span> <span class="dt">Node</span> (x<span class="op">-</span><span class="dv">1</span>) (dec l) (dec r)</a>
<a class="sourceLine" id="cb121-4" title="4"> inc (<span class="dt">Node</span> x l r) <span class="ot">=</span> <span class="dt">Node</span> (x<span class="op">+</span><span class="dv">1</span>) (inc l) (inc r)</a></code></pre></div>
</div>
<p>Another way to create this tree is to use a higher order function. This function should be similar to <code>map</code>, but should work on <code>BinTree</code> instead of list. Here is such a function:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb122"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb122-1" title="1"><span class="co">-- apply a function to each node of Tree</span></a>
<a class="sourceLine" id="cb122-2" title="2"><span class="ot">treeMap ::</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> <span class="dt">BinTree</span> a <span class="ot">-&gt;</span> <span class="dt">BinTree</span> b</a>
<a class="sourceLine" id="cb122-3" title="3">treeMap f <span class="dt">Empty</span> <span class="ot">=</span> <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb122-4" title="4">treeMap f (<span class="dt">Node</span> x left right) <span class="ot">=</span> <span class="dt">Node</span> (f x)</a>
<a class="sourceLine" id="cb122-5" title="5"> (treeMap f left)</a>
<a class="sourceLine" id="cb122-6" title="6"> (treeMap f right)</a></code></pre></div>
</div>
<p><em>Hint</em>: I wont talk more about this here. If you are interested in the generalization of <code>map</code> to other data structures, search for functor and <code>fmap</code>.</p>
<p>Our definition is now:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb123"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb123-1" title="1"><span class="ot">infTreeTwo ::</span> <span class="dt">BinTree</span> <span class="dt">Int</span></a>
<a class="sourceLine" id="cb123-2" title="2">infTreeTwo <span class="ot">=</span> <span class="dt">Node</span> <span class="dv">0</span> (treeMap (\x <span class="ot">-&gt;</span> x<span class="op">-</span><span class="dv">1</span>) infTreeTwo)</a>
<a class="sourceLine" id="cb123-3" title="3"> (treeMap (\x <span class="ot">-&gt;</span> x<span class="op">+</span><span class="dv">1</span>) infTreeTwo)</a></code></pre></div>
</div>
<p>Look at the result for</p>
<div class="sourceCode" id="cb124"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb124-1" title="1">main <span class="ot">=</span> <span class="fu">print</span> <span class="op">$</span> treeTakeDepth <span class="dv">4</span> infTreeTwo</a></code></pre></div>
<pre><code>&lt; 0
: |-- -1
: | |-- -2
: | | |-- -3
: | | `-- -1
: | `-- 0
: | |-- -1
: | `-- 1
: `-- 1
: |-- 0
: | |-- -1
: | `-- 1
: `-- 2
: |-- 1
: `-- 3</code></pre>
<div style="display:none">
<div class="codehighlight">
<div class="sourceCode" id="cb126"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb126-1" title="1">main <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb126-2" title="2"> <span class="fu">print</span> <span class="op">$</span> treeTakeDepth <span class="dv">4</span> nullTree</a>
<a class="sourceLine" id="cb126-3" title="3"> <span class="fu">print</span> <span class="op">$</span> treeTakeDepth <span class="dv">4</span> infTreeTwo</a></code></pre></div>
</div>
</div>
<p><a href="code/02_Hard_Part/41_Infinites_Structures.lhs" class="cut">02_Hard_Part/<strong>41_Infinites_Structures.lhs</strong> </a></p>
<h2 id="hell-difficulty-part">
Hell Difficulty Part
</h2>
<p>Congratulations for getting so far! Now, some of the really hardcore stuff can start.</p>
<p>If you are like me, you should get the functional style. You should also understand a bit more the advantages of laziness by default. But you also dont really understand where to start in order to make a real program. And in particular:</p>
<ul>
<li>How do you deal with effects?</li>
<li>Why is there a strange imperative-like notation for dealing with IO?</li>
</ul>
<p>Be prepared, the answers might be complex. But they are all very rewarding.</p>
<hr />
<p><a href="code/03_Hell/01_IO/01_progressive_io_example.lhs" class="cut">03_Hell/01_IO/<strong>01_progressive_io_example.lhs</strong></a></p>
<h3 id="deal-with-io">
Deal With IO
</h3>
<div>
<img src="../../../../Scratch/img/blog/Haskell-the-Hard-Way/magritte_carte_blanche.jpg" alt="Magritte, Carte blanche" />
</div>
<blockquote>
<p><span class="sc"><abbr title="Too long; didn't read">tl;dr</abbr>: </span></p>
<p>A typical function doing <code>IO</code> looks a lot like an imperative program:</p>
<pre><code>f :: IO a
f = do
x &lt;- action1
action2 x
y &lt;- action3
action4 x y</code></pre>
<ul>
<li>To set a value to an object we use <code>&lt;-</code> .</li>
<li>The type of each line is <code>IO *</code>; in this example:
<ul>
<li><code>action1 :: IO b</code></li>
<li><code>action2 x :: IO ()</code></li>
<li><code>action3 :: IO c</code></li>
<li><code>action4 x y :: IO a</code></li>
<li><code>x :: b</code>, <code>y :: c</code></li>
</ul></li>
<li>Few objects have the type <code>IO a</code>, this should help you choose. In particular you cannot use pure functions directly here. To use pure functions you could do <code>action2 (purefunction x)</code> for example.</li>
</ul>
</blockquote>
<p>In this section, I will explain how to use IO, not how it works. Youll see how Haskell separates the pure from the impure parts of the program.</p>
<p>Dont stop because youre trying to understand the details of the syntax. Answers will come in the next section.</p>
<p>What to achieve?</p>
<blockquote>
<p>Ask a user to enter a list of numbers. Print the sum of the numbers</p>
</blockquote>
<div class="codehighlight">
<div class="sourceCode" id="cb128"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb128-1" title="1"><span class="ot">toList ::</span> <span class="dt">String</span> <span class="ot">-&gt;</span> [<span class="dt">Integer</span>]</a>
<a class="sourceLine" id="cb128-2" title="2">toList input <span class="ot">=</span> <span class="fu">read</span> (<span class="st">&quot;[&quot;</span> <span class="op">++</span> input <span class="op">++</span> <span class="st">&quot;]&quot;</span>)</a>
<a class="sourceLine" id="cb128-3" title="3"></a>
<a class="sourceLine" id="cb128-4" title="4">main <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb128-5" title="5"> <span class="fu">putStrLn</span> <span class="st">&quot;Enter a list of numbers (separated by comma):&quot;</span></a>
<a class="sourceLine" id="cb128-6" title="6"> input <span class="ot">&lt;-</span> <span class="fu">getLine</span></a>
<a class="sourceLine" id="cb128-7" title="7"> <span class="fu">print</span> <span class="op">$</span> <span class="fu">sum</span> (toList input)</a></code></pre></div>
</div>
<p>It should be straightforward to understand the behavior of this program. Lets analyze the types in more detail.</p>
<pre><code>putStrLn :: String -&gt; IO ()
getLine :: IO String
print :: Show a =&gt; a -&gt; IO ()</code></pre>
<p>Or more interestingly, we note that each expression in the <code>do</code> block has a type of <code>IO a</code>.</p>
<pre>
main = do
putStrLn "Enter ... " :: <span class="high">IO ()</span>
getLine :: <span class="high">IO String</span>
print Something :: <span class="high">IO ()</span>
</pre>
<p>We should also pay attention to the effect of the <code>&lt;-</code> symbol.</p>
<pre><code>do
x &lt;- something</code></pre>
<p>If <code>something :: IO a</code> then <code>x :: a</code>.</p>
<p>Another important note about using <code>IO</code>: All lines in a do block must be of one of the two forms:</p>
<pre><code>action1 :: IO a
-- in this case, generally a = ()</code></pre>
<p>ou</p>
<pre><code>value &lt;- action2 -- where
-- action2 :: IO b
-- value :: b</code></pre>
<p>These two kinds of line will correspond to two different ways of sequencing actions. The meaning of this sentence should be clearer by the end of the next section.</p>
<p><a href="code/03_Hell/01_IO/01_progressive_io_example.lhs" class="cut">03_Hell/01_IO/<strong>01_progressive_io_example.lhs</strong> </a></p>
<hr />
<p><a href="code/03_Hell/01_IO/02_progressive_io_example.lhs" class="cut">03_Hell/01_IO/<strong>02_progressive_io_example.lhs</strong></a></p>
<p>Now lets see how this program behaves. For example, what happens if the user enters something strange? Lets try:</p>
<pre><code> % runghc 02_progressive_io_example.lhs
Enter a list of numbers (separated by comma):
foo
Prelude.read: no parse</code></pre>
<p>Argh! An evil error message and a crash! Our first improvement will simply be to answer with a more friendly message.</p>
<p>In order to do this, we must detect that something went wrong. Here is one way to do this: use the type <code>Maybe</code>. This is a very common type in Haskell.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb134"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb134-1" title="1"><span class="kw">import</span> <span class="dt">Data.Maybe</span></a></code></pre></div>
</div>
<p>What is this thing? <code>Maybe</code> is a type which takes one parameter. Its definition is:</p>
<div class="sourceCode" id="cb135"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb135-1" title="1"><span class="kw">data</span> <span class="dt">Maybe</span> a <span class="ot">=</span> <span class="dt">Nothing</span> <span class="op">|</span> <span class="dt">Just</span> a</a></code></pre></div>
<p>This is a nice way to tell there was an error while trying to create/compute a value. The <code>maybeRead</code> function is a great example of this. This is a function similar to the function <code>read</code><a href="#fn4" class="footnote-ref" id="fnref4"><sup>4</sup></a>, but if something goes wrong the returned value is <code>Nothing</code>. If the value is right, it returns <code>Just &lt;the value&gt;</code>. Dont try to understand too much of this function. I use a lower level function than <code>read</code>: <code>reads</code>.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb136"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb136-1" title="1"><span class="ot">maybeRead ::</span> <span class="dt">Read</span> a <span class="ot">=&gt;</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a</a>
<a class="sourceLine" id="cb136-2" title="2">maybeRead s <span class="ot">=</span> <span class="kw">case</span> <span class="fu">reads</span> s <span class="kw">of</span></a>
<a class="sourceLine" id="cb136-3" title="3"> [(x,<span class="st">&quot;&quot;</span>)] <span class="ot">-&gt;</span> <span class="dt">Just</span> x</a>
<a class="sourceLine" id="cb136-4" title="4"> _ <span class="ot">-&gt;</span> <span class="dt">Nothing</span></a></code></pre></div>
</div>
<p>Now to be a bit more readable, we define a function which goes like this: If the string has the wrong format, it will return <code>Nothing</code>. Otherwise, for example for “1,2,3”, it will return <code>Just [1,2,3]</code>.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb137"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb137-1" title="1"><span class="ot">getListFromString ::</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">Maybe</span> [<span class="dt">Integer</span>]</a>
<a class="sourceLine" id="cb137-2" title="2">getListFromString str <span class="ot">=</span> maybeRead <span class="op">$</span> <span class="st">&quot;[&quot;</span> <span class="op">++</span> str <span class="op">++</span> <span class="st">&quot;]&quot;</span></a></code></pre></div>
</div>
<p>We simply have to test the value in our main function.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb138"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb138-1" title="1"><span class="ot">main ::</span> <span class="dt">IO</span> ()</a>
<a class="sourceLine" id="cb138-2" title="2">main <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb138-3" title="3"> <span class="fu">putStrLn</span> <span class="st">&quot;Enter a list of numbers (separated by comma):&quot;</span></a>
<a class="sourceLine" id="cb138-4" title="4"> input <span class="ot">&lt;-</span> <span class="fu">getLine</span></a>
<a class="sourceLine" id="cb138-5" title="5"> <span class="kw">let</span> maybeList <span class="ot">=</span> getListFromString input <span class="kw">in</span></a>
<a class="sourceLine" id="cb138-6" title="6"> <span class="kw">case</span> maybeList <span class="kw">of</span></a>
<a class="sourceLine" id="cb138-7" title="7"> <span class="dt">Just</span> l <span class="ot">-&gt;</span> <span class="fu">print</span> (<span class="fu">sum</span> l)</a>
<a class="sourceLine" id="cb138-8" title="8"> <span class="dt">Nothing</span> <span class="ot">-&gt;</span> <span class="fu">error</span> <span class="st">&quot;Bad format. Good Bye.&quot;</span></a></code></pre></div>
</div>
<p>In case of error, we display a nice error message.</p>
<p>Note that the type of each expression in the mains <code>do</code> block remains of the form <code>IO a</code>. The only strange construction is <code>error</code>. Ill just say here that <code>error msg</code> takes the needed type (here <code>IO ()</code>).</p>
<p>One very important thing to note is the type of all the functions defined so far. There is only one function which contains <code>IO</code> in its type: <code>main</code>. This means main is impure. But main uses <code>getListFromString</code> which is pure. So its clear just by looking at declared types which functions are pure and which are impure.</p>
<p>Why does purity matter? Among the many advantages, here are three:</p>
<ul>
<li>It is far easier to think about pure code than impure code.</li>
<li>Purity protects you from all the hard-to-reproduce bugs that are due to side effects.</li>
<li>You can evaluate pure functions in any order or in parallel without risk.</li>
</ul>
<p>This is why you should generally put as most code as possible inside pure functions.</p>
<p><a href="code/03_Hell/01_IO/02_progressive_io_example.lhs" class="cut">03_Hell/01_IO/<strong>02_progressive_io_example.lhs</strong> </a></p>
<hr />
<p><a href="code/03_Hell/01_IO/03_progressive_io_example.lhs" class="cut">03_Hell/01_IO/<strong>03_progressive_io_example.lhs</strong></a></p>
<p>Our next iteration will be to prompt the user again and again until she enters a valid answer.</p>
<p>We keep the first part:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb139"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb139-1" title="1"><span class="kw">import</span> <span class="dt">Data.Maybe</span></a>
<a class="sourceLine" id="cb139-2" title="2"></a>
<a class="sourceLine" id="cb139-3" title="3"><span class="ot">maybeRead ::</span> <span class="dt">Read</span> a <span class="ot">=&gt;</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a</a>
<a class="sourceLine" id="cb139-4" title="4">maybeRead s <span class="ot">=</span> <span class="kw">case</span> <span class="fu">reads</span> s <span class="kw">of</span></a>
<a class="sourceLine" id="cb139-5" title="5"> [(x,<span class="st">&quot;&quot;</span>)] <span class="ot">-&gt;</span> <span class="dt">Just</span> x</a>
<a class="sourceLine" id="cb139-6" title="6"> _ <span class="ot">-&gt;</span> <span class="dt">Nothing</span></a>
<a class="sourceLine" id="cb139-7" title="7"><span class="ot">getListFromString ::</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">Maybe</span> [<span class="dt">Integer</span>]</a>
<a class="sourceLine" id="cb139-8" title="8">getListFromString str <span class="ot">=</span> maybeRead <span class="op">$</span> <span class="st">&quot;[&quot;</span> <span class="op">++</span> str <span class="op">++</span> <span class="st">&quot;]&quot;</span></a></code></pre></div>
</div>
<p>Now we create a function which will ask the user for an list of integers until the input is right.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb140"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb140-1" title="1"><span class="ot">askUser ::</span> <span class="dt">IO</span> [<span class="dt">Integer</span>]</a>
<a class="sourceLine" id="cb140-2" title="2">askUser <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb140-3" title="3"> <span class="fu">putStrLn</span> <span class="st">&quot;Enter a list of numbers (separated by comma):&quot;</span></a>
<a class="sourceLine" id="cb140-4" title="4"> input <span class="ot">&lt;-</span> <span class="fu">getLine</span></a>
<a class="sourceLine" id="cb140-5" title="5"> <span class="kw">let</span> maybeList <span class="ot">=</span> getListFromString input <span class="kw">in</span></a>
<a class="sourceLine" id="cb140-6" title="6"> <span class="kw">case</span> maybeList <span class="kw">of</span></a>
<a class="sourceLine" id="cb140-7" title="7"> <span class="dt">Just</span> l <span class="ot">-&gt;</span> <span class="fu">return</span> l</a>
<a class="sourceLine" id="cb140-8" title="8"> <span class="dt">Nothing</span> <span class="ot">-&gt;</span> askUser</a></code></pre></div>
</div>
<p>This function is of type <code>IO [Integer]</code>. Such a type means that we retrieved a value of type <code>[Integer]</code> through some IO actions. Some people might explain while waving their hands:</p>
<blockquote>
<p>«This is an <code>[Integer]</code> inside an <code>IO</code>»</p>
</blockquote>
<p>If you want to understand the details behind all of this, youll have to read the next section. But really, if you just want to <em>use</em> IO just practice a little and remember to think about the type.</p>
<p>Finally our main function is much simpler:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb141"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb141-1" title="1"><span class="ot">main ::</span> <span class="dt">IO</span> ()</a>
<a class="sourceLine" id="cb141-2" title="2">main <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb141-3" title="3"> list <span class="ot">&lt;-</span> askUser</a>
<a class="sourceLine" id="cb141-4" title="4"> <span class="fu">print</span> <span class="op">$</span> <span class="fu">sum</span> list</a></code></pre></div>
</div>
<p>We have finished with our introduction to <code>IO</code>. This was quite fast. Here are the main things to remember:</p>
<ul>
<li>in the <code>do</code> block, each expression must have the type <code>IO a</code>. You are then limited with regard to the range of expressions available. For example, <code>getLine</code>, <code>print</code>, <code>putStrLn</code>, etc…</li>
<li>Try to externalize the pure functions as much as possible.</li>
<li>the <code>IO a</code> type means: an IO <em>action</em> which returns an element of type <code>a</code>. <code>IO</code> represents actions; under the hood, <code>IO a</code> is the type of a function. Read the next section if you are curious.</li>
</ul>
<p>If you practice a bit, you should be able to <em>use</em> <code>IO</code>.</p>
<blockquote>
<p><em>Exercises</em>:</p>
<ul>
<li>Make a program that sums all of its arguments. Hint: use the function <code>getArgs</code>.</li>
</ul>
</blockquote>
<p><a href="code/03_Hell/01_IO/03_progressive_io_example.lhs" class="cut">03_Hell/01_IO/<strong>03_progressive_io_example.lhs</strong> </a></p>
<h3 id="io-trick-explained">
IO trick explained
</h3>
<div>
<img src="../../../../Scratch/img/blog/Haskell-the-Hard-Way/magritte_pipe.jpg" alt="Magritte, ceci n" />
</div>
<blockquote>
<p>Here is a <span class="sc"><abbr title="Too long; didn't read">tl;dr</abbr>: </span> for this section.</p>
<p>To separate pure and impure parts, <code>main</code> is defined as a function which modifies the state of the world.</p>
<pre><code>main :: World -&gt; World</code></pre>
<p>A function is guaranteed to have side effects only if it has this type. But look at a typical main function:</p>
<pre><code>
main w0 =
let (v1,w1) = action1 w0 in
let (v2,w2) = action2 v1 w1 in
let (v3,w3) = action3 v2 w2 in
action4 v3 w3</code></pre>
<p>We have a lot of temporary elements (here <code>w1</code>, <code>w2</code> and <code>w3</code>) which must be passed on to the next action.</p>
<p>We create a function <code>bind</code> or <code>(&gt;&gt;=)</code>. With <code>bind</code> we dont need temporary names anymore.</p>
<pre><code>main =
action1 &gt;&gt;= action2 &gt;&gt;= action3 &gt;&gt;= action4</code></pre>
<p>Bonus: Haskell has syntactical sugar for us:</p>
<pre><code>main = do
v1 &lt;- action1
v2 &lt;- action2 v1
v3 &lt;- action3 v2
action4 v3</code></pre>
</blockquote>
<p>Why did we use this strange syntax, and what exactly is this <code>IO</code> type? It looks a bit like magic.</p>
<p>For now lets just forget all about the pure parts of our program, and focus on the impure parts:</p>
<div class="sourceCode" id="cb146"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb146-1" title="1"><span class="ot">askUser ::</span> <span class="dt">IO</span> [<span class="dt">Integer</span>]</a>
<a class="sourceLine" id="cb146-2" title="2">askUser <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb146-3" title="3"> <span class="fu">putStrLn</span> <span class="st">&quot;Enter a list of numbers (separated by commas):&quot;</span></a>
<a class="sourceLine" id="cb146-4" title="4"> input <span class="ot">&lt;-</span> <span class="fu">getLine</span></a>
<a class="sourceLine" id="cb146-5" title="5"> <span class="kw">let</span> maybeList <span class="ot">=</span> getListFromString input <span class="kw">in</span></a>
<a class="sourceLine" id="cb146-6" title="6"> <span class="kw">case</span> maybeList <span class="kw">of</span></a>
<a class="sourceLine" id="cb146-7" title="7"> <span class="dt">Just</span> l <span class="ot">-&gt;</span> <span class="fu">return</span> l</a>
<a class="sourceLine" id="cb146-8" title="8"> <span class="dt">Nothing</span> <span class="ot">-&gt;</span> askUser</a>
<a class="sourceLine" id="cb146-9" title="9"></a>
<a class="sourceLine" id="cb146-10" title="10"><span class="ot">main ::</span> <span class="dt">IO</span> ()</a>
<a class="sourceLine" id="cb146-11" title="11">main <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb146-12" title="12"> list <span class="ot">&lt;-</span> askUser</a>
<a class="sourceLine" id="cb146-13" title="13"> <span class="fu">print</span> <span class="op">$</span> <span class="fu">sum</span> list</a></code></pre></div>
<p>First remark: this looks imperative. Haskell is powerful enough to make impure code look imperative. For example, if you wish you could create a <code>while</code> in Haskell. In fact, for dealing with <code>IO</code>, an imperative style is generally more appropriate.</p>
<p>But you should have noticed that the notation is a bit unusual. Here is why, in detail.</p>
<p>In an impure language, the state of the world can be seen as a huge hidden global variable. This hidden variable is accessible by all functions of your language. For example, you can read and write a file in any function. Whether a file exists or not is a difference in the possible states that the world can take.</p>
<p>In Haskell the current state of the world is not hidden. Rather, it is <em>explicitly</em> said that <code>main</code> is a function that <em>potentially</em> changes the state of the world. Its type is then something like:</p>
<div class="sourceCode" id="cb147"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb147-1" title="1"><span class="ot">main ::</span> <span class="dt">World</span> <span class="ot">-&gt;</span> <span class="dt">World</span></a></code></pre></div>
<p>Not all functions may access this variable. Those which have access to this variable are impure. Functions to which the world variable isnt provided are pure<a href="#fn5" class="footnote-ref" id="fnref5"><sup>5</sup></a>.</p>
<p>Haskell considers the state of the world as an input variable to <code>main</code>. But the real type of main is closer to this one<a href="#fn6" class="footnote-ref" id="fnref6"><sup>6</sup></a>:</p>
<div class="sourceCode" id="cb148"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb148-1" title="1"><span class="ot">main ::</span> <span class="dt">World</span> <span class="ot">-&gt;</span> ((),<span class="dt">World</span>)</a></code></pre></div>
<p>The <code>()</code> type is the unit type. Nothing to see here.</p>
<p>Now lets rewrite our main function with this in mind:</p>
<div class="sourceCode" id="cb149"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb149-1" title="1">main w0 <span class="ot">=</span></a>
<a class="sourceLine" id="cb149-2" title="2"> <span class="kw">let</span> (list,w1) <span class="ot">=</span> askUser w0 <span class="kw">in</span></a>
<a class="sourceLine" id="cb149-3" title="3"> <span class="kw">let</span> (x,w2) <span class="ot">=</span> <span class="fu">print</span> (<span class="fu">sum</span> list,w1) <span class="kw">in</span></a>
<a class="sourceLine" id="cb149-4" title="4"> x</a></code></pre></div>
<p>First, we note that all functions which have side effects must have the type:</p>
<div class="sourceCode" id="cb150"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb150-1" title="1"><span class="dt">World</span> <span class="ot">-&gt;</span> (a,<span class="dt">World</span>)</a></code></pre></div>
<p>where <code>a</code> is the type of the result. For example, a <code>getChar</code> function should have the type <code>World -&gt; (Char, World)</code>.</p>
<p>Another thing to note is the trick to fix the order of evaluation. In Haskell, in order to evaluate <code>f a b</code>, you have many choices:</p>
<ul>
<li>first eval <code>a</code> then <code>b</code> then <code>f a b</code></li>
<li>first eval <code>b</code> then <code>a</code> then <code>f a b</code>.</li>
<li>eval <code>a</code> and <code>b</code> in parallel then <code>f a b</code></li>
</ul>
<p>This is true because were working in a pure part of the language.</p>
<p>Now, if you look at the main function, it is clear you must eval the first line before the second one since to evaluate the second line you have to get a parameter given by the evaluation of the first line.</p>
<p>This trick works like a charm. The compiler will at each step provide a pointer to a new real world id. Under the hood, <code>print</code> will evaluate as:</p>
<ul>
<li>print something on the screen</li>
<li>modify the id of the world</li>
<li>evaluate as <code>((),new world id)</code>.</li>
</ul>
<p>Now, if you look at the style of the main function, it is clearly awkward. Lets try to do the same to the <code>askUser</code> function:</p>
<div class="sourceCode" id="cb151"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb151-1" title="1"><span class="ot">askUser ::</span> <span class="dt">World</span> <span class="ot">-&gt;</span> ([<span class="dt">Integer</span>],<span class="dt">World</span>)</a></code></pre></div>
<p>Before:</p>
<div class="sourceCode" id="cb152"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb152-1" title="1"><span class="ot">askUser ::</span> <span class="dt">IO</span> [<span class="dt">Integer</span>]</a>
<a class="sourceLine" id="cb152-2" title="2">askUser <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb152-3" title="3"> <span class="fu">putStrLn</span> <span class="st">&quot;Enter a list of numbers:&quot;</span></a>
<a class="sourceLine" id="cb152-4" title="4"> input <span class="ot">&lt;-</span> <span class="fu">getLine</span></a>
<a class="sourceLine" id="cb152-5" title="5"> <span class="kw">let</span> maybeList <span class="ot">=</span> getListFromString input <span class="kw">in</span></a>
<a class="sourceLine" id="cb152-6" title="6"> <span class="kw">case</span> maybeList <span class="kw">of</span></a>
<a class="sourceLine" id="cb152-7" title="7"> <span class="dt">Just</span> l <span class="ot">-&gt;</span> <span class="fu">return</span> l</a>
<a class="sourceLine" id="cb152-8" title="8"> <span class="dt">Nothing</span> <span class="ot">-&gt;</span> askUser</a></code></pre></div>
<p>After:</p>
<div class="sourceCode" id="cb153"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb153-1" title="1">askUser w0 <span class="ot">=</span></a>
<a class="sourceLine" id="cb153-2" title="2"> <span class="kw">let</span> (_,w1) <span class="ot">=</span> <span class="fu">putStrLn</span> <span class="st">&quot;Enter a list of numbers:&quot;</span> <span class="kw">in</span></a>
<a class="sourceLine" id="cb153-3" title="3"> <span class="kw">let</span> (input,w2) <span class="ot">=</span> <span class="fu">getLine</span> w1 <span class="kw">in</span></a>
<a class="sourceLine" id="cb153-4" title="4"> <span class="kw">let</span> (l,w3) <span class="ot">=</span> <span class="kw">case</span> getListFromString input <span class="kw">of</span></a>
<a class="sourceLine" id="cb153-5" title="5"> <span class="dt">Just</span> l <span class="ot">-&gt;</span> (l,w2)</a>
<a class="sourceLine" id="cb153-6" title="6"> <span class="dt">Nothing</span> <span class="ot">-&gt;</span> askUser w2</a>
<a class="sourceLine" id="cb153-7" title="7"> <span class="kw">in</span></a>
<a class="sourceLine" id="cb153-8" title="8"> (l,w3)</a></code></pre></div>
<p>This is similar, but awkward. Look at all these temporary <code>w?</code> names.</p>
<p>The lesson is: naive IO implementation in Pure functional languages is awkward!</p>
<p>Fortunately, there is a better way to handle this problem. We see a pattern. Each line is of the form:</p>
<div class="sourceCode" id="cb154"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb154-1" title="1"><span class="kw">let</span> (y,w') <span class="ot">=</span> action x w <span class="kw">in</span></a></code></pre></div>
<p>Even if for some lines the first <code>x</code> argument isnt needed. The output type is a couple, <code>(answer, newWorldValue)</code>. Each function <code>f</code> must have a type similar to:</p>
<div class="sourceCode" id="cb155"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb155-1" title="1"><span class="ot">f ::</span> <span class="dt">World</span> <span class="ot">-&gt;</span> (a,<span class="dt">World</span>)</a></code></pre></div>
<p>Not only this, but we can also note that we always follow the same usage pattern:</p>
<div class="sourceCode" id="cb156"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb156-1" title="1"><span class="kw">let</span> (y,w1) <span class="ot">=</span> action1 w0 <span class="kw">in</span></a>
<a class="sourceLine" id="cb156-2" title="2"><span class="kw">let</span> (z,w2) <span class="ot">=</span> action2 w1 <span class="kw">in</span></a>
<a class="sourceLine" id="cb156-3" title="3"><span class="kw">let</span> (t,w3) <span class="ot">=</span> action3 w2 <span class="kw">in</span></a>
<a class="sourceLine" id="cb156-4" title="4"><span class="op">...</span></a></code></pre></div>
<p>Each action can take from 0 to n parameters. And in particular, each action can take a parameter from the result of a line above.</p>
<p>For example, we could also have:</p>
<div class="sourceCode" id="cb157"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb157-1" title="1"><span class="kw">let</span> (_,w1) <span class="ot">=</span> action1 x w0 <span class="kw">in</span></a>
<a class="sourceLine" id="cb157-2" title="2"><span class="kw">let</span> (z,w2) <span class="ot">=</span> action2 w1 <span class="kw">in</span></a>
<a class="sourceLine" id="cb157-3" title="3"><span class="kw">let</span> (_,w3) <span class="ot">=</span> action3 z w2 <span class="kw">in</span></a>
<a class="sourceLine" id="cb157-4" title="4"><span class="op">...</span></a></code></pre></div>
<p>With, of course: <code>actionN w :: (World) -&gt; (a,World)</code>.</p>
<blockquote>
<p>IMPORTANT: there are only two important patterns to consider:</p>
<pre><code>let (x,w1) = action1 w0 in
let (y,w2) = action2 x w1 in</code></pre>
<p>and</p>
<pre><code>let (_,w1) = action1 w0 in
let (y,w2) = action2 w1 in</code></pre>
</blockquote>
<div>
<img src="../../../../Scratch/img/blog/Haskell-the-Hard-Way/jocker_pencil_trick.jpg" alt="Jocker pencil trick" class="left" />
</div>
<p>Now, we will do a magic trick. We will make the temporary world symbols “disappear”. We will <code>bind</code> the two lines. Lets define the <code>bind</code> function. Its type is quite intimidating at first:</p>
<div class="sourceCode" id="cb160"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb160-1" title="1"><span class="ot">bind ::</span> (<span class="dt">World</span> <span class="ot">-&gt;</span> (a,<span class="dt">World</span>))</a>
<a class="sourceLine" id="cb160-2" title="2"> <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> (<span class="dt">World</span> <span class="ot">-&gt;</span> (b,<span class="dt">World</span>)))</a>
<a class="sourceLine" id="cb160-3" title="3"> <span class="ot">-&gt;</span> (<span class="dt">World</span> <span class="ot">-&gt;</span> (b,<span class="dt">World</span>))</a></code></pre></div>
<p>But remember that <code>(World -&gt; (a,World))</code> is the type for an IO action. Now lets rename it for clarity:</p>
<div class="sourceCode" id="cb161"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb161-1" title="1"><span class="kw">type</span> <span class="dt">IO</span> a <span class="ot">=</span> <span class="dt">World</span> <span class="ot">-&gt;</span> (a, <span class="dt">World</span>)</a></code></pre></div>
<p>Some examples of functions:</p>
<div class="sourceCode" id="cb162"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb162-1" title="1"><span class="fu">getLine</span><span class="ot"> ::</span> <span class="dt">IO</span> <span class="dt">String</span></a>
<a class="sourceLine" id="cb162-2" title="2"><span class="fu">print</span><span class="ot"> ::</span> <span class="dt">Show</span> a <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">IO</span> ()</a></code></pre></div>
<p><code>getLine</code> is an IO action which takes world as a parameter and returns a couple <code>(String, World)</code>. This can be summarized as: <code>getLine</code> is of type <code>IO String</code>, which we also see as an IO action which will return a String “embeded inside an IO”.</p>
<p>The function <code>print</code> is also interesting. It takes one argument which can be shown. In fact it takes two arguments. The first is the value to print and the other is the state of world. It then returns a couple of type <code>((), World)</code>. This means that it changes the state of the world, but doesnt yield any more data.</p>
<p>This new <code>IO a</code> type helps us simplify the type of <code>bind</code>:</p>
<div class="sourceCode" id="cb163"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb163-1" title="1"><span class="ot">bind ::</span> <span class="dt">IO</span> a</a>
<a class="sourceLine" id="cb163-2" title="2"> <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> <span class="dt">IO</span> b)</a>
<a class="sourceLine" id="cb163-3" title="3"> <span class="ot">-&gt;</span> <span class="dt">IO</span> b</a></code></pre></div>
<p>It says that <code>bind</code> takes two IO actions as parameters and returns another IO action.</p>
<p>Now, remember the <em>important</em> patterns. The first was:</p>
<div class="sourceCode" id="cb164"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb164-1" title="1">pattern1 w0 <span class="ot">=</span> </a>
<a class="sourceLine" id="cb164-2" title="2"> <span class="kw">let</span> (x,w1) <span class="ot">=</span> action1 w0 <span class="kw">in</span></a>
<a class="sourceLine" id="cb164-3" title="3"> <span class="kw">let</span> (y,w2) <span class="ot">=</span> action2 x w1 <span class="kw">in</span></a>
<a class="sourceLine" id="cb164-4" title="4"> (y,w2)</a></code></pre></div>
<p>Look at the types:</p>
<div class="sourceCode" id="cb165"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb165-1" title="1"><span class="ot">action1 ::</span> <span class="dt">IO</span> a</a>
<a class="sourceLine" id="cb165-2" title="2"><span class="ot">action2 ::</span> a <span class="ot">-&gt;</span> <span class="dt">IO</span> b</a>
<a class="sourceLine" id="cb165-3" title="3"><span class="ot">pattern1 ::</span> <span class="dt">IO</span> b</a></code></pre></div>
<p>Doesnt it seem familiar?</p>
<div class="sourceCode" id="cb166"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb166-1" title="1">(bind action1 action2) w0 <span class="ot">=</span></a>
<a class="sourceLine" id="cb166-2" title="2"> <span class="kw">let</span> (x, w1) <span class="ot">=</span> action1 w0</a>
<a class="sourceLine" id="cb166-3" title="3"> (y, w2) <span class="ot">=</span> action2 x w1</a>
<a class="sourceLine" id="cb166-4" title="4"> <span class="kw">in</span> (y, w2)</a></code></pre></div>
<p>The idea is to hide the World argument with this function. Lets go: As an example imagine if we wanted to simulate:</p>
<div class="sourceCode" id="cb167"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb167-1" title="1"><span class="kw">let</span> (line1, w1) <span class="ot">=</span> <span class="fu">getLine</span> w0 <span class="kw">in</span></a>
<a class="sourceLine" id="cb167-2" title="2"><span class="kw">let</span> ((), w2) <span class="ot">=</span> <span class="fu">print</span> line1 <span class="kw">in</span></a>
<a class="sourceLine" id="cb167-3" title="3">((), w2)</a></code></pre></div>
<p>Now, using the <code>bind</code> function:</p>
<div class="sourceCode" id="cb168"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb168-1" title="1">(res, w2) <span class="ot">=</span> (bind <span class="fu">getLine</span> <span class="fu">print</span>) w0</a></code></pre></div>
<p>As print is of type <code>Show a =&gt; a -&gt; (World -&gt; ((), World))</code>, we know <code>res = ()</code> (<code>unit</code> type). If you didnt see what was magic here, lets try with three lines this time.</p>
<div class="sourceCode" id="cb169"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb169-1" title="1"><span class="kw">let</span> (line1,w1) <span class="ot">=</span> <span class="fu">getLine</span> w0 <span class="kw">in</span></a>
<a class="sourceLine" id="cb169-2" title="2"><span class="kw">let</span> (line2,w2) <span class="ot">=</span> <span class="fu">getLine</span> w1 <span class="kw">in</span></a>
<a class="sourceLine" id="cb169-3" title="3"><span class="kw">let</span> ((),w3) <span class="ot">=</span> <span class="fu">print</span> (line1 <span class="op">++</span> line2) <span class="kw">in</span></a>
<a class="sourceLine" id="cb169-4" title="4">((),w3)</a></code></pre></div>
<p>Which is equivalent to:</p>
<div class="sourceCode" id="cb170"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb170-1" title="1">(res,w3) <span class="ot">=</span> (bind <span class="fu">getLine</span> (\line1 <span class="ot">-&gt;</span></a>
<a class="sourceLine" id="cb170-2" title="2"> (bind <span class="fu">getLine</span> (\line2 <span class="ot">-&gt;</span></a>
<a class="sourceLine" id="cb170-3" title="3"> <span class="fu">print</span> (line1 <span class="op">++</span> line2))))) w0</a></code></pre></div>
<p>Didnt you notice something? Yes, no temporary World variables are used anywhere! This is <em>MA</em>. <em>GIC</em>.</p>
<p>We can use a better notation. Lets use <code>(&gt;&gt;=)</code> instead of <code>bind</code>. <code>(&gt;&gt;=)</code> is an infix function like <code>(+)</code>; reminder <code>3 + 4 ⇔ (+) 3 4</code></p>
<div class="sourceCode" id="cb171"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb171-1" title="1">(res,w3) <span class="ot">=</span> (<span class="fu">getLine</span> <span class="op">&gt;&gt;=</span></a>
<a class="sourceLine" id="cb171-2" title="2"> (\line1 <span class="ot">-&gt;</span> <span class="fu">getLine</span> <span class="op">&gt;&gt;=</span></a>
<a class="sourceLine" id="cb171-3" title="3"> (\line2 <span class="ot">-&gt;</span> <span class="fu">print</span> (line1 <span class="op">++</span> line2)))) w0</a></code></pre></div>
<p>fr; Haskell a confectionné du sucre syntaxique pour vous : Ho Ho Ho! Merry Christmas Everyone! Haskell has made syntactical sugar for us:</p>
<div class="sourceCode" id="cb172"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb172-1" title="1"><span class="kw">do</span></a>
<a class="sourceLine" id="cb172-2" title="2"> x <span class="ot">&lt;-</span> action1</a>
<a class="sourceLine" id="cb172-3" title="3"> y <span class="ot">&lt;-</span> action2</a>
<a class="sourceLine" id="cb172-4" title="4"> z <span class="ot">&lt;-</span> action3</a>
<a class="sourceLine" id="cb172-5" title="5"> <span class="op">...</span></a></code></pre></div>
<p>Is replaced by:</p>
<div class="sourceCode" id="cb173"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb173-1" title="1">action1 <span class="op">&gt;&gt;=</span> (\x <span class="ot">-&gt;</span></a>
<a class="sourceLine" id="cb173-2" title="2">action2 <span class="op">&gt;&gt;=</span> (\y <span class="ot">-&gt;</span></a>
<a class="sourceLine" id="cb173-3" title="3">action3 <span class="op">&gt;&gt;=</span> (\z <span class="ot">-&gt;</span></a>
<a class="sourceLine" id="cb173-4" title="4"><span class="op">...</span></a>
<a class="sourceLine" id="cb173-5" title="5">)))</a></code></pre></div>
<p>Note that you can use <code>x</code> in <code>action2</code> and <code>x</code> and <code>y</code> in <code>action3</code>.</p>
<p>But what about the lines not using the <code>&lt;-</code>? Easy, another function <code>blindBind</code>:</p>
<div class="sourceCode" id="cb174"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb174-1" title="1"><span class="ot">blindBind ::</span> <span class="dt">IO</span> a <span class="ot">-&gt;</span> <span class="dt">IO</span> b <span class="ot">-&gt;</span> <span class="dt">IO</span> b</a>
<a class="sourceLine" id="cb174-2" title="2">blindBind action1 action2 w0 <span class="ot">=</span></a>
<a class="sourceLine" id="cb174-3" title="3"> bind action (\_ <span class="ot">-&gt;</span> action2) w0</a></code></pre></div>
<p>I didnt simplify this definition for the purposes of clarity. Of course, we can use a better notation: well use the <code>(&gt;&gt;)</code> operator.</p>
<p>And</p>
<div class="sourceCode" id="cb175"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb175-1" title="1"><span class="kw">do</span></a>
<a class="sourceLine" id="cb175-2" title="2"> action1</a>
<a class="sourceLine" id="cb175-3" title="3"> action2</a>
<a class="sourceLine" id="cb175-4" title="4"> action3</a></code></pre></div>
<p>Is transformed into</p>
<div class="sourceCode" id="cb176"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb176-1" title="1">action1 <span class="op">&gt;&gt;</span></a>
<a class="sourceLine" id="cb176-2" title="2">action2 <span class="op">&gt;&gt;</span></a>
<a class="sourceLine" id="cb176-3" title="3">action3</a></code></pre></div>
<p>Also, another function is quite useful.</p>
<div class="sourceCode" id="cb177"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb177-1" title="1"><span class="ot">putInIO ::</span> a <span class="ot">-&gt;</span> <span class="dt">IO</span> a</a>
<a class="sourceLine" id="cb177-2" title="2">putInIO x <span class="ot">=</span> <span class="dt">IO</span> (\w <span class="ot">-&gt;</span> (x,w))</a></code></pre></div>
<p>This is the general way to put pure values inside the “IO context”. The general name for <code>putInIO</code> is <code>return</code>. This is quite a bad name when you learn Haskell. <code>return</code> is very different from what you might be used to.</p>
<hr />
<p><a href="code/03_Hell/01_IO/21_Detailled_IO.lhs" class="cut">03_Hell/01_IO/<strong>21_Detailled_IO.lhs</strong></a></p>
<p>To finish, lets translate our example:</p>
<div class="sourceCode" id="cb178"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb178-1" title="1"></a>
<a class="sourceLine" id="cb178-2" title="2"><span class="ot">askUser ::</span> <span class="dt">IO</span> [<span class="dt">Integer</span>]</a>
<a class="sourceLine" id="cb178-3" title="3">askUser <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb178-4" title="4"> <span class="fu">putStrLn</span> <span class="st">&quot;Enter a list of numbers (separated by commas):&quot;</span></a>
<a class="sourceLine" id="cb178-5" title="5"> input <span class="ot">&lt;-</span> <span class="fu">getLine</span></a>
<a class="sourceLine" id="cb178-6" title="6"> <span class="kw">let</span> maybeList <span class="ot">=</span> getListFromString input <span class="kw">in</span></a>
<a class="sourceLine" id="cb178-7" title="7"> <span class="kw">case</span> maybeList <span class="kw">of</span></a>
<a class="sourceLine" id="cb178-8" title="8"> <span class="dt">Just</span> l <span class="ot">-&gt;</span> <span class="fu">return</span> l</a>
<a class="sourceLine" id="cb178-9" title="9"> <span class="dt">Nothing</span> <span class="ot">-&gt;</span> askUser</a>
<a class="sourceLine" id="cb178-10" title="10"></a>
<a class="sourceLine" id="cb178-11" title="11"><span class="ot">main ::</span> <span class="dt">IO</span> ()</a>
<a class="sourceLine" id="cb178-12" title="12">main <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb178-13" title="13"> list <span class="ot">&lt;-</span> askUser</a>
<a class="sourceLine" id="cb178-14" title="14"> <span class="fu">print</span> <span class="op">$</span> <span class="fu">sum</span> list</a></code></pre></div>
<p>Is translated into:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb179"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb179-1" title="1"><span class="kw">import</span> <span class="dt">Data.Maybe</span></a>
<a class="sourceLine" id="cb179-2" title="2"></a>
<a class="sourceLine" id="cb179-3" title="3"><span class="ot">maybeRead ::</span> <span class="dt">Read</span> a <span class="ot">=&gt;</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a</a>
<a class="sourceLine" id="cb179-4" title="4">maybeRead s <span class="ot">=</span> <span class="kw">case</span> <span class="fu">reads</span> s <span class="kw">of</span></a>
<a class="sourceLine" id="cb179-5" title="5"> [(x,<span class="st">&quot;&quot;</span>)] <span class="ot">-&gt;</span> <span class="dt">Just</span> x</a>
<a class="sourceLine" id="cb179-6" title="6"> _ <span class="ot">-&gt;</span> <span class="dt">Nothing</span></a>
<a class="sourceLine" id="cb179-7" title="7"><span class="ot">getListFromString ::</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">Maybe</span> [<span class="dt">Integer</span>]</a>
<a class="sourceLine" id="cb179-8" title="8">getListFromString str <span class="ot">=</span> maybeRead <span class="op">$</span> <span class="st">&quot;[&quot;</span> <span class="op">++</span> str <span class="op">++</span> <span class="st">&quot;]&quot;</span></a>
<a class="sourceLine" id="cb179-9" title="9"><span class="ot">askUser ::</span> <span class="dt">IO</span> [<span class="dt">Integer</span>]</a>
<a class="sourceLine" id="cb179-10" title="10">askUser <span class="ot">=</span> </a>
<a class="sourceLine" id="cb179-11" title="11"> <span class="fu">putStrLn</span> <span class="st">&quot;Enter a list of numbers (sep. by commas):&quot;</span> <span class="op">&gt;&gt;</span></a>
<a class="sourceLine" id="cb179-12" title="12"> <span class="fu">getLine</span> <span class="op">&gt;&gt;=</span> \input <span class="ot">-&gt;</span></a>
<a class="sourceLine" id="cb179-13" title="13"> <span class="kw">let</span> maybeList <span class="ot">=</span> getListFromString input <span class="kw">in</span></a>
<a class="sourceLine" id="cb179-14" title="14"> <span class="kw">case</span> maybeList <span class="kw">of</span></a>
<a class="sourceLine" id="cb179-15" title="15"> <span class="dt">Just</span> l <span class="ot">-&gt;</span> <span class="fu">return</span> l</a>
<a class="sourceLine" id="cb179-16" title="16"> <span class="dt">Nothing</span> <span class="ot">-&gt;</span> askUser</a>
<a class="sourceLine" id="cb179-17" title="17"></a>
<a class="sourceLine" id="cb179-18" title="18"><span class="ot">main ::</span> <span class="dt">IO</span> ()</a>
<a class="sourceLine" id="cb179-19" title="19">main <span class="ot">=</span> askUser <span class="op">&gt;&gt;=</span></a>
<a class="sourceLine" id="cb179-20" title="20"> \list <span class="ot">-&gt;</span> <span class="fu">print</span> <span class="op">$</span> <span class="fu">sum</span> list</a></code></pre></div>
</div>
<p>You can compile this code to verify that it works.</p>
<p>Imagine what it would look like without the <code>(&gt;&gt;)</code> and <code>(&gt;&gt;=)</code>.</p>
<p><a href="code/03_Hell/01_IO/21_Detailled_IO.lhs" class="cut">03_Hell/01_IO/<strong>21_Detailled_IO.lhs</strong> </a></p>
<hr />
<p><a href="code/03_Hell/02_Monads/10_Monads.lhs" class="cut">03_Hell/02_Monads/<strong>10_Monads.lhs</strong></a></p>
<h3 id="monads">
Monads
</h3>
<div>
<img src="../../../../Scratch/img/blog/Haskell-the-Hard-Way/dali_reve.jpg" alt="Dali, reve. It represents a weapon out of the mouth of a tiger, itself out of the mouth of another tiger, itself out of the mouth of a fish itself out of a grenade. I could have choosen a picture of the Human centipede as it is a very good representation of what a monad really is. But just to think about it, I find this disgusting and that wasn" />
</div>
<p>Now the secret can be revealed: <code>IO</code> is a <em>monad</em>. Being a monad means you have access to some syntactical sugar with the <code>do</code> notation. But mainly, you have access to a coding pattern which will ease the flow of your code.</p>
<blockquote>
<p><strong>Important remarks</strong>:</p>
<ul>
<li>Monad are not necessarily about effects! There are a lot of <em>pure</em> monads.</li>
<li>Monad are more about sequencing</li>
</ul>
</blockquote>
<p>In Haskell, <code>Monad</code> is a type class. To be an instance of this type class, you must provide the functions <code>(&gt;&gt;=)</code> and <code>return</code>. The function <code>(&gt;&gt;)</code> is derived from <code>(&gt;&gt;=)</code>. Here is how the type class <code>Monad</code> is declared (basically):</p>
<div class="sourceCode" id="cb180"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb180-1" title="1"><span class="kw">class</span> <span class="dt">Monad</span> m <span class="kw">where</span></a>
<a class="sourceLine" id="cb180-2" title="2"><span class="ot"> (&gt;&gt;=) ::</span> m a <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> m b) <span class="ot">-&gt;</span> m b</a>
<a class="sourceLine" id="cb180-3" title="3"><span class="ot"> return ::</span> a <span class="ot">-&gt;</span> m a</a>
<a class="sourceLine" id="cb180-4" title="4"></a>
<a class="sourceLine" id="cb180-5" title="5"><span class="ot"> (&gt;&gt;) ::</span> m a <span class="ot">-&gt;</span> m b <span class="ot">-&gt;</span> m b</a>
<a class="sourceLine" id="cb180-6" title="6"> f <span class="op">&gt;&gt;</span> g <span class="ot">=</span> f <span class="op">&gt;&gt;=</span> \_ <span class="ot">-&gt;</span> g</a>
<a class="sourceLine" id="cb180-7" title="7"></a>
<a class="sourceLine" id="cb180-8" title="8"> <span class="co">-- You should generally safely ignore this function</span></a>
<a class="sourceLine" id="cb180-9" title="9"> <span class="co">-- which I believe exists for historical reasons</span></a>
<a class="sourceLine" id="cb180-10" title="10"><span class="ot"> fail ::</span> <span class="dt">String</span> <span class="ot">-&gt;</span> m a</a>
<a class="sourceLine" id="cb180-11" title="11"> <span class="fu">fail</span> <span class="ot">=</span> <span class="fu">error</span></a></code></pre></div>
<blockquote>
<p>Remarks:</p>
<ul>
<li>the keyword <code>class</code> is not your friend. A Haskell class is <em>not</em> a class of the kind you will find in object-oriented programming. A Haskell class has a lot of similarities with Java interfaces. A better word would have been <code>typeclass</code>, since that means a set of types. For a type to belong to a class, all functions of the class must be provided for this type.</li>
<li>In this particular example of type class, the type <code>m</code> must be a type that takes an argument. for example <code>IO a</code>, but also <code>Maybe a</code>, <code>[a]</code>, etc…</li>
<li>To be a useful monad, your function must obey some rules. If your construction does not obey these rules strange things might happens:</li>
</ul>
</blockquote>
<blockquote>
<pre><code>return a &gt;&gt;= k == k a
m &gt;&gt;= return == m
m &gt;&gt;= (\x -&gt; k x &gt;&gt;= h) == (m &gt;&gt;= k) &gt;&gt;= h</code></pre>
</blockquote>
<h4 id="maybe-monad">
Maybe is a monad
</h4>
<p>There are a lot of different types that are instances of <code>Monad</code>. One of the easiest to describe is <code>Maybe</code>. If you have a sequence of <code>Maybe</code> values, you can use monads to manipulate them. It is particularly useful to remove very deep <code>if..then..else..</code> constructions.</p>
<p>Imagine a complex bank operation. You are eligible to gain about 700€ only if you can afford to follow a list of operations without your balance dipping below zero.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb182"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb182-1" title="1">deposit value account <span class="ot">=</span> account <span class="op">+</span> value</a>
<a class="sourceLine" id="cb182-2" title="2">withdraw value account <span class="ot">=</span> account <span class="op">-</span> value</a>
<a class="sourceLine" id="cb182-3" title="3"></a>
<a class="sourceLine" id="cb182-4" title="4"><span class="ot">eligible ::</span> (<span class="dt">Num</span> a,<span class="dt">Ord</span> a) <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Bool</span></a>
<a class="sourceLine" id="cb182-5" title="5">eligible account <span class="ot">=</span></a>
<a class="sourceLine" id="cb182-6" title="6"> <span class="kw">let</span> account1 <span class="ot">=</span> deposit <span class="dv">100</span> account <span class="kw">in</span></a>
<a class="sourceLine" id="cb182-7" title="7"> <span class="kw">if</span> (account1 <span class="op">&lt;</span> <span class="dv">0</span>)</a>
<a class="sourceLine" id="cb182-8" title="8"> <span class="kw">then</span> <span class="dt">False</span></a>
<a class="sourceLine" id="cb182-9" title="9"> <span class="kw">else</span></a>
<a class="sourceLine" id="cb182-10" title="10"> <span class="kw">let</span> account2 <span class="ot">=</span> withdraw <span class="dv">200</span> account1 <span class="kw">in</span></a>
<a class="sourceLine" id="cb182-11" title="11"> <span class="kw">if</span> (account2 <span class="op">&lt;</span> <span class="dv">0</span>)</a>
<a class="sourceLine" id="cb182-12" title="12"> <span class="kw">then</span> <span class="dt">False</span></a>
<a class="sourceLine" id="cb182-13" title="13"> <span class="kw">else</span></a>
<a class="sourceLine" id="cb182-14" title="14"> <span class="kw">let</span> account3 <span class="ot">=</span> deposit <span class="dv">100</span> account2 <span class="kw">in</span></a>
<a class="sourceLine" id="cb182-15" title="15"> <span class="kw">if</span> (account3 <span class="op">&lt;</span> <span class="dv">0</span>)</a>
<a class="sourceLine" id="cb182-16" title="16"> <span class="kw">then</span> <span class="dt">False</span></a>
<a class="sourceLine" id="cb182-17" title="17"> <span class="kw">else</span></a>
<a class="sourceLine" id="cb182-18" title="18"> <span class="kw">let</span> account4 <span class="ot">=</span> withdraw <span class="dv">300</span> account3 <span class="kw">in</span></a>
<a class="sourceLine" id="cb182-19" title="19"> <span class="kw">if</span> (account4 <span class="op">&lt;</span> <span class="dv">0</span>)</a>
<a class="sourceLine" id="cb182-20" title="20"> <span class="kw">then</span> <span class="dt">False</span></a>
<a class="sourceLine" id="cb182-21" title="21"> <span class="kw">else</span></a>
<a class="sourceLine" id="cb182-22" title="22"> <span class="kw">let</span> account5 <span class="ot">=</span> deposit <span class="dv">1000</span> account4 <span class="kw">in</span></a>
<a class="sourceLine" id="cb182-23" title="23"> <span class="kw">if</span> (account5 <span class="op">&lt;</span> <span class="dv">0</span>)</a>
<a class="sourceLine" id="cb182-24" title="24"> <span class="kw">then</span> <span class="dt">False</span></a>
<a class="sourceLine" id="cb182-25" title="25"> <span class="kw">else</span></a>
<a class="sourceLine" id="cb182-26" title="26"> <span class="dt">True</span></a>
<a class="sourceLine" id="cb182-27" title="27"></a>
<a class="sourceLine" id="cb182-28" title="28">main <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb182-29" title="29"> <span class="fu">print</span> <span class="op">$</span> eligible <span class="dv">300</span> <span class="co">-- True</span></a>
<a class="sourceLine" id="cb182-30" title="30"> <span class="fu">print</span> <span class="op">$</span> eligible <span class="dv">299</span> <span class="co">-- False</span></a></code></pre></div>
</div>
<p><a href="code/03_Hell/02_Monads/10_Monads.lhs" class="cut">03_Hell/02_Monads/<strong>10_Monads.lhs</strong> </a></p>
<hr />
<p><a href="code/03_Hell/02_Monads/11_Monads.lhs" class="cut">03_Hell/02_Monads/<strong>11_Monads.lhs</strong></a></p>
<p>Now, lets make it better using Maybe and the fact that it is a Monad</p>
<div class="codehighlight">
<div class="sourceCode" id="cb183"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb183-1" title="1"><span class="ot">deposit ::</span> (<span class="dt">Num</span> a) <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a</a>
<a class="sourceLine" id="cb183-2" title="2">deposit value account <span class="ot">=</span> <span class="dt">Just</span> (account <span class="op">+</span> value)</a>
<a class="sourceLine" id="cb183-3" title="3"></a>
<a class="sourceLine" id="cb183-4" title="4"><span class="ot">withdraw ::</span> (<span class="dt">Num</span> a,<span class="dt">Ord</span> a) <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a</a>
<a class="sourceLine" id="cb183-5" title="5">withdraw value account <span class="ot">=</span> <span class="kw">if</span> (account <span class="op">&lt;</span> value) </a>
<a class="sourceLine" id="cb183-6" title="6"> <span class="kw">then</span> <span class="dt">Nothing</span> </a>
<a class="sourceLine" id="cb183-7" title="7"> <span class="kw">else</span> <span class="dt">Just</span> (account <span class="op">-</span> value)</a>
<a class="sourceLine" id="cb183-8" title="8"></a>
<a class="sourceLine" id="cb183-9" title="9"><span class="ot">eligible ::</span> (<span class="dt">Num</span> a, <span class="dt">Ord</span> a) <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> <span class="dt">Bool</span></a>
<a class="sourceLine" id="cb183-10" title="10">eligible account <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb183-11" title="11"> account1 <span class="ot">&lt;-</span> deposit <span class="dv">100</span> account </a>
<a class="sourceLine" id="cb183-12" title="12"> account2 <span class="ot">&lt;-</span> withdraw <span class="dv">200</span> account1 </a>
<a class="sourceLine" id="cb183-13" title="13"> account3 <span class="ot">&lt;-</span> deposit <span class="dv">100</span> account2 </a>
<a class="sourceLine" id="cb183-14" title="14"> account4 <span class="ot">&lt;-</span> withdraw <span class="dv">300</span> account3 </a>
<a class="sourceLine" id="cb183-15" title="15"> account5 <span class="ot">&lt;-</span> deposit <span class="dv">1000</span> account4</a>
<a class="sourceLine" id="cb183-16" title="16"> <span class="dt">Just</span> <span class="dt">True</span></a>
<a class="sourceLine" id="cb183-17" title="17"></a>
<a class="sourceLine" id="cb183-18" title="18">main <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb183-19" title="19"> <span class="fu">print</span> <span class="op">$</span> eligible <span class="dv">300</span> <span class="co">-- Just True</span></a>
<a class="sourceLine" id="cb183-20" title="20"> <span class="fu">print</span> <span class="op">$</span> eligible <span class="dv">299</span> <span class="co">-- Nothing</span></a></code></pre></div>
</div>
<p><a href="code/03_Hell/02_Monads/11_Monads.lhs" class="cut">03_Hell/02_Monads/<strong>11_Monads.lhs</strong> </a></p>
<hr />
<p><a href="code/03_Hell/02_Monads/12_Monads.lhs" class="cut">03_Hell/02_Monads/<strong>12_Monads.lhs</strong></a></p>
<p>Not bad, but we can make it even better:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb184"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb184-1" title="1"><span class="ot">deposit ::</span> (<span class="dt">Num</span> a) <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a</a>
<a class="sourceLine" id="cb184-2" title="2">deposit value account <span class="ot">=</span> <span class="dt">Just</span> (account <span class="op">+</span> value)</a>
<a class="sourceLine" id="cb184-3" title="3"></a>
<a class="sourceLine" id="cb184-4" title="4"><span class="ot">withdraw ::</span> (<span class="dt">Num</span> a,<span class="dt">Ord</span> a) <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a</a>
<a class="sourceLine" id="cb184-5" title="5">withdraw value account <span class="ot">=</span> <span class="kw">if</span> (account <span class="op">&lt;</span> value) </a>
<a class="sourceLine" id="cb184-6" title="6"> <span class="kw">then</span> <span class="dt">Nothing</span> </a>
<a class="sourceLine" id="cb184-7" title="7"> <span class="kw">else</span> <span class="dt">Just</span> (account <span class="op">-</span> value)</a>
<a class="sourceLine" id="cb184-8" title="8"></a>
<a class="sourceLine" id="cb184-9" title="9"><span class="ot">eligible ::</span> (<span class="dt">Num</span> a, <span class="dt">Ord</span> a) <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> <span class="dt">Bool</span></a>
<a class="sourceLine" id="cb184-10" title="10">eligible account <span class="ot">=</span></a>
<a class="sourceLine" id="cb184-11" title="11"> deposit <span class="dv">100</span> account <span class="op">&gt;&gt;=</span></a>
<a class="sourceLine" id="cb184-12" title="12"> withdraw <span class="dv">200</span> <span class="op">&gt;&gt;=</span></a>
<a class="sourceLine" id="cb184-13" title="13"> deposit <span class="dv">100</span> <span class="op">&gt;&gt;=</span></a>
<a class="sourceLine" id="cb184-14" title="14"> withdraw <span class="dv">300</span> <span class="op">&gt;&gt;=</span></a>
<a class="sourceLine" id="cb184-15" title="15"> deposit <span class="dv">1000</span> <span class="op">&gt;&gt;</span></a>
<a class="sourceLine" id="cb184-16" title="16"> <span class="fu">return</span> <span class="dt">True</span></a>
<a class="sourceLine" id="cb184-17" title="17"></a>
<a class="sourceLine" id="cb184-18" title="18">main <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb184-19" title="19"> <span class="fu">print</span> <span class="op">$</span> eligible <span class="dv">300</span> <span class="co">-- Just True</span></a>
<a class="sourceLine" id="cb184-20" title="20"> <span class="fu">print</span> <span class="op">$</span> eligible <span class="dv">299</span> <span class="co">-- Nothing</span></a></code></pre></div>
</div>
<p>We have proven that Monads are a good way to make our code more elegant. Note this idea of code organization, in particular for <code>Maybe</code> can be used in most imperative languages. In fact, this is the kind of construction we make naturally.</p>
<blockquote>
<p>An important remark:</p>
<p>The first element in the sequence being evaluated to <code>Nothing</code> will stop the complete evaluation. This means you dont execute all lines. You get this for free, thanks to laziness.</p>
</blockquote>
<p>You could also replay these example with the definition of <code>(&gt;&gt;=)</code> for <code>Maybe</code> in mind:</p>
<div class="sourceCode" id="cb185"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb185-1" title="1"><span class="kw">instance</span> <span class="dt">Monad</span> <span class="dt">Maybe</span> <span class="kw">where</span></a>
<a class="sourceLine" id="cb185-2" title="2"><span class="ot"> (&gt;&gt;=) ::</span> <span class="dt">Maybe</span> a <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> b) <span class="ot">-&gt;</span> <span class="dt">Maybe</span> b</a>
<a class="sourceLine" id="cb185-3" title="3"> <span class="dt">Nothing</span> <span class="op">&gt;&gt;=</span> _ <span class="ot">=</span> <span class="dt">Nothing</span></a>
<a class="sourceLine" id="cb185-4" title="4"> (<span class="dt">Just</span> x) <span class="op">&gt;&gt;=</span> f <span class="ot">=</span> f x</a>
<a class="sourceLine" id="cb185-5" title="5"></a>
<a class="sourceLine" id="cb185-6" title="6"> <span class="fu">return</span> x <span class="ot">=</span> <span class="dt">Just</span> x</a></code></pre></div>
<p>The <code>Maybe</code> monad proved to be useful while being a very simple example. We saw the utility of the <code>IO</code> monad. But now for a cooler example, lists.</p>
<p><a href="code/03_Hell/02_Monads/12_Monads.lhs" class="cut">03_Hell/02_Monads/<strong>12_Monads.lhs</strong> </a></p>
<hr />
<p><a href="code/03_Hell/02_Monads/13_Monads.lhs" class="cut">03_Hell/02_Monads/<strong>13_Monads.lhs</strong></a></p>
<h4 id="the-list-monad">
The list monad
</h4>
<div>
<img src="../../../../Scratch/img/blog/Haskell-the-Hard-Way/golconde.jpg" alt="Golconde de Magritte" />
</div>
<p>The list monad helps us to simulate non-deterministic computations. Here we go:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb186"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb186-1" title="1"><span class="kw">import</span> <span class="dt">Control.Monad</span> (guard)</a>
<a class="sourceLine" id="cb186-2" title="2"></a>
<a class="sourceLine" id="cb186-3" title="3">allCases <span class="ot">=</span> [<span class="dv">1</span><span class="op">..</span><span class="dv">10</span>]</a>
<a class="sourceLine" id="cb186-4" title="4"></a>
<a class="sourceLine" id="cb186-5" title="5"><span class="ot">resolve ::</span> [(<span class="dt">Int</span>,<span class="dt">Int</span>,<span class="dt">Int</span>)]</a>
<a class="sourceLine" id="cb186-6" title="6">resolve <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb186-7" title="7"> x <span class="ot">&lt;-</span> allCases</a>
<a class="sourceLine" id="cb186-8" title="8"> y <span class="ot">&lt;-</span> allCases</a>
<a class="sourceLine" id="cb186-9" title="9"> z <span class="ot">&lt;-</span> allCases</a>
<a class="sourceLine" id="cb186-10" title="10"> guard <span class="op">$</span> <span class="dv">4</span><span class="op">*</span>x <span class="op">+</span> <span class="dv">2</span><span class="op">*</span>y <span class="op">&lt;</span> z</a>
<a class="sourceLine" id="cb186-11" title="11"> <span class="fu">return</span> (x,y,z)</a>
<a class="sourceLine" id="cb186-12" title="12"></a>
<a class="sourceLine" id="cb186-13" title="13">main <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb186-14" title="14"> <span class="fu">print</span> resolve</a></code></pre></div>
</div>
<p>MA. GIC.&nbsp;:</p>
<pre><code>[(1,1,7),(1,1,8),(1,1,9),(1,1,10),(1,2,9),(1,2,10)]</code></pre>
<p>For the list monad, there is also this syntactic sugar:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb188"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb188-1" title="1"> <span class="fu">print</span> <span class="op">$</span> [ (x,y,z) <span class="op">|</span> x <span class="ot">&lt;-</span> allCases,</a>
<a class="sourceLine" id="cb188-2" title="2"> y <span class="ot">&lt;-</span> allCases,</a>
<a class="sourceLine" id="cb188-3" title="3"> z <span class="ot">&lt;-</span> allCases,</a>
<a class="sourceLine" id="cb188-4" title="4"> <span class="dv">4</span><span class="op">*</span>x <span class="op">+</span> <span class="dv">2</span><span class="op">*</span>y <span class="op">&lt;</span> z ]</a></code></pre></div>
</div>
<p>I wont list all the monads, since there are many of them. Using monads simplifies the manipulation of several notions in pure languages. In particular, monads are very useful for:</p>
<ul>
<li>IO,</li>
<li>non-deterministic computation,</li>
<li>generating pseudo random numbers,</li>
<li>keeping configuration state,</li>
<li>writing state,</li>
<li></li>
</ul>
<p>If you have followed me until here, then youve done it! You know monads<a href="#fn7" class="footnote-ref" id="fnref7"><sup>7</sup></a>!</p>
<p><a href="code/03_Hell/02_Monads/13_Monads.lhs" class="cut">03_Hell/02_Monads/<strong>13_Monads.lhs</strong> </a></p>
<h2 id="appendix">
Appendix
</h2>
<p>This section is not so much about learning Haskell. It is just here to discuss some details further.</p>
<hr />
<p><a href="code/04_Appendice/01_More_on_infinite_trees/10_Infinite_Trees.lhs" class="cut">04_Appendice/01_More_on_infinite_trees/<strong>10_Infinite_Trees.lhs</strong></a></p>
<h3 id="more-on-infinite-tree">
More on Infinite Tree
</h3>
<p>In the section <a href="#infinite-structures">Infinite Structures</a> we saw some simple constructions. Unfortunately we removed two properties from our tree:</p>
<ol type="1">
<li>no duplicate node value</li>
<li>well ordered tree</li>
</ol>
<p>In this section we will try to keep the first property. Concerning the second one, we must relax it but well discuss how to keep it as much as possible.</p>
<div style="display:none">
<p>This code is mostly the same as the one in the <a href="#trees">tree section</a>.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb189"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb189-1" title="1"><span class="kw">import</span> <span class="dt">Data.List</span></a>
<a class="sourceLine" id="cb189-2" title="2"><span class="kw">data</span> <span class="dt">BinTree</span> a <span class="ot">=</span> <span class="dt">Empty</span> </a>
<a class="sourceLine" id="cb189-3" title="3"> <span class="op">|</span> <span class="dt">Node</span> a (<span class="dt">BinTree</span> a) (<span class="dt">BinTree</span> a) </a>
<a class="sourceLine" id="cb189-4" title="4"> <span class="kw">deriving</span> (<span class="dt">Eq</span>,<span class="dt">Ord</span>)</a>
<a class="sourceLine" id="cb189-5" title="5"></a>
<a class="sourceLine" id="cb189-6" title="6"><span class="co">-- declare BinTree a to be an instance of Show</span></a>
<a class="sourceLine" id="cb189-7" title="7"><span class="kw">instance</span> (<span class="dt">Show</span> a) <span class="ot">=&gt;</span> <span class="dt">Show</span> (<span class="dt">BinTree</span> a) <span class="kw">where</span></a>
<a class="sourceLine" id="cb189-8" title="8"> <span class="co">-- will start by a '&lt;' before the root</span></a>
<a class="sourceLine" id="cb189-9" title="9"> <span class="co">-- and put a : a begining of line</span></a>
<a class="sourceLine" id="cb189-10" title="10"> <span class="fu">show</span> t <span class="ot">=</span> <span class="st">&quot;&lt; &quot;</span> <span class="op">++</span> replace <span class="ch">'\n'</span> <span class="st">&quot;\n: &quot;</span> (treeshow <span class="st">&quot;&quot;</span> t)</a>
<a class="sourceLine" id="cb189-11" title="11"> <span class="kw">where</span></a>
<a class="sourceLine" id="cb189-12" title="12"> treeshow pref <span class="dt">Empty</span> <span class="ot">=</span> <span class="st">&quot;&quot;</span></a>
<a class="sourceLine" id="cb189-13" title="13"> treeshow pref (<span class="dt">Node</span> x <span class="dt">Empty</span> <span class="dt">Empty</span>) <span class="ot">=</span> </a>
<a class="sourceLine" id="cb189-14" title="14"> (pshow pref x)</a>
<a class="sourceLine" id="cb189-15" title="15"></a>
<a class="sourceLine" id="cb189-16" title="16"> treeshow pref (<span class="dt">Node</span> x left <span class="dt">Empty</span>) <span class="ot">=</span> </a>
<a class="sourceLine" id="cb189-17" title="17"> (pshow pref x) <span class="op">++</span> <span class="st">&quot;\n&quot;</span> <span class="op">++</span></a>
<a class="sourceLine" id="cb189-18" title="18"> (showSon pref <span class="st">&quot;`--&quot;</span> <span class="st">&quot; &quot;</span> left)</a>
<a class="sourceLine" id="cb189-19" title="19"></a>
<a class="sourceLine" id="cb189-20" title="20"> treeshow pref (<span class="dt">Node</span> x <span class="dt">Empty</span> right) <span class="ot">=</span> </a>
<a class="sourceLine" id="cb189-21" title="21"> (pshow pref x) <span class="op">++</span> <span class="st">&quot;\n&quot;</span> <span class="op">++</span></a>
<a class="sourceLine" id="cb189-22" title="22"> (showSon pref <span class="st">&quot;`--&quot;</span> <span class="st">&quot; &quot;</span> right)</a>
<a class="sourceLine" id="cb189-23" title="23"></a>
<a class="sourceLine" id="cb189-24" title="24"> treeshow pref (<span class="dt">Node</span> x left right) <span class="ot">=</span> </a>
<a class="sourceLine" id="cb189-25" title="25"> (pshow pref x) <span class="op">++</span> <span class="st">&quot;\n&quot;</span> <span class="op">++</span></a>
<a class="sourceLine" id="cb189-26" title="26"> (showSon pref <span class="st">&quot;|--&quot;</span> <span class="st">&quot;| &quot;</span> left) <span class="op">++</span> <span class="st">&quot;\n&quot;</span> <span class="op">++</span></a>
<a class="sourceLine" id="cb189-27" title="27"> (showSon pref <span class="st">&quot;`--&quot;</span> <span class="st">&quot; &quot;</span> right)</a>
<a class="sourceLine" id="cb189-28" title="28"></a>
<a class="sourceLine" id="cb189-29" title="29"> <span class="co">-- show a tree using some prefixes to make it nice</span></a>
<a class="sourceLine" id="cb189-30" title="30"> showSon pref before next t <span class="ot">=</span> </a>
<a class="sourceLine" id="cb189-31" title="31"> pref <span class="op">++</span> before <span class="op">++</span> treeshow (pref <span class="op">++</span> next) t</a>
<a class="sourceLine" id="cb189-32" title="32"></a>
<a class="sourceLine" id="cb189-33" title="33"> <span class="co">-- pshow replace &quot;\n&quot; by &quot;\n&quot;++pref</span></a>
<a class="sourceLine" id="cb189-34" title="34"> pshow pref x <span class="ot">=</span> replace <span class="ch">'\n'</span> (<span class="st">&quot;\n&quot;</span><span class="op">++</span>pref) (<span class="fu">show</span> x)</a>
<a class="sourceLine" id="cb189-35" title="35"></a>
<a class="sourceLine" id="cb189-36" title="36"> <span class="co">-- replace on char by another string</span></a>
<a class="sourceLine" id="cb189-37" title="37"> replace c new string <span class="ot">=</span></a>
<a class="sourceLine" id="cb189-38" title="38"> <span class="fu">concatMap</span> (change c new) string</a>
<a class="sourceLine" id="cb189-39" title="39"> <span class="kw">where</span></a>
<a class="sourceLine" id="cb189-40" title="40"> change c new x </a>
<a class="sourceLine" id="cb189-41" title="41"> <span class="op">|</span> x <span class="op">==</span> c <span class="ot">=</span> new</a>
<a class="sourceLine" id="cb189-42" title="42"> <span class="op">|</span> <span class="fu">otherwise</span> <span class="ot">=</span> x<span class="op">:</span>[] <span class="co">-- &quot;x&quot;</span></a></code></pre></div>
</div>
</div>
<p>Our first step is to create some pseudo-random number list:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb190"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb190-1" title="1">shuffle <span class="ot">=</span> <span class="fu">map</span> (\x <span class="ot">-&gt;</span> (x<span class="op">*</span><span class="dv">3123</span>) <span class="ot">`mod`</span> <span class="dv">4331</span>) [<span class="dv">1</span><span class="op">..</span>]</a></code></pre></div>
</div>
<p>Just as a reminder, here is the definition of <code>treeFromList</code></p>
<div class="codehighlight">
<div class="sourceCode" id="cb191"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb191-1" title="1"><span class="ot">treeFromList ::</span> (<span class="dt">Ord</span> a) <span class="ot">=&gt;</span> [a] <span class="ot">-&gt;</span> <span class="dt">BinTree</span> a</a>
<a class="sourceLine" id="cb191-2" title="2">treeFromList [] <span class="ot">=</span> <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb191-3" title="3">treeFromList (x<span class="op">:</span>xs) <span class="ot">=</span> <span class="dt">Node</span> x (treeFromList (<span class="fu">filter</span> (<span class="op">&lt;</span>x) xs))</a>
<a class="sourceLine" id="cb191-4" title="4"> (treeFromList (<span class="fu">filter</span> (<span class="op">&gt;</span>x) xs))</a></code></pre></div>
</div>
<p>and <code>treeTakeDepth</code>:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb192"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb192-1" title="1">treeTakeDepth _ <span class="dt">Empty</span> <span class="ot">=</span> <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb192-2" title="2">treeTakeDepth <span class="dv">0</span> _ <span class="ot">=</span> <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb192-3" title="3">treeTakeDepth n (<span class="dt">Node</span> x left right) <span class="ot">=</span> <span class="kw">let</span></a>
<a class="sourceLine" id="cb192-4" title="4"> nl <span class="ot">=</span> treeTakeDepth (n<span class="op">-</span><span class="dv">1</span>) left</a>
<a class="sourceLine" id="cb192-5" title="5"> nr <span class="ot">=</span> treeTakeDepth (n<span class="op">-</span><span class="dv">1</span>) right</a>
<a class="sourceLine" id="cb192-6" title="6"> <span class="kw">in</span></a>
<a class="sourceLine" id="cb192-7" title="7"> <span class="dt">Node</span> x nl nr</a></code></pre></div>
</div>
<p>See the result of:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb193"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb193-1" title="1">main <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb193-2" title="2"> <span class="fu">putStrLn</span> <span class="st">&quot;take 10 shuffle&quot;</span></a>
<a class="sourceLine" id="cb193-3" title="3"> <span class="fu">print</span> <span class="op">$</span> <span class="fu">take</span> <span class="dv">10</span> shuffle</a>
<a class="sourceLine" id="cb193-4" title="4"> <span class="fu">putStrLn</span> <span class="st">&quot;\ntreeTakeDepth 4 (treeFromList shuffle)&quot;</span></a>
<a class="sourceLine" id="cb193-5" title="5"> <span class="fu">print</span> <span class="op">$</span> treeTakeDepth <span class="dv">4</span> (treeFromList shuffle)</a></code></pre></div>
</div>
<pre><code>% runghc 02_Hard_Part/41_Infinites_Structures.lhs
take 10 shuffle
[3123,1915,707,3830,2622,1414,206,3329,2121,913]
treeTakeDepth 4 (treeFromList shuffle)
&lt; 3123
: |--1915
: | |--707
: | | |--206
: | | `--1414
: | `--2622
: | |--2121
: | `--2828
: `--3830
: |--3329
: | |--3240
: | `--3535
: `--4036
: |--3947
: `--4242</code></pre>
<p>Yay! It ends! Beware though, it will only work if you always have something to put into a branch.</p>
<p>For example</p>
<div class="sourceCode" id="cb195"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb195-1" title="1">treeTakeDepth <span class="dv">4</span> (treeFromList [<span class="dv">1</span><span class="op">..</span>]) </a></code></pre></div>
<p>will loop forever. Simply because it will try to access the head of <code>filter (&lt;1) [2..]</code>. But <code>filter</code> is not smart enought to understand that the result is the empty list.</p>
<p>Nonetheless, it is still a very cool example of what non strict programs have to offer.</p>
<p>Left as an exercise to the reader:</p>
<ul>
<li>Prove the existence of a number <code>n</code> so that <code>treeTakeDepth n (treeFromList shuffle)</code> will enter an infinite loop.</li>
<li>Find an upper bound for <code>n</code>.</li>
<li>Prove there is no <code>shuffle</code> list so that, for any depth, the program ends.</li>
</ul>
<p><a href="code/04_Appendice/01_More_on_infinite_trees/10_Infinite_Trees.lhs" class="cut">04_Appendice/01_More_on_infinite_trees/<strong>10_Infinite_Trees.lhs</strong> </a></p>
<hr />
<p><a href="code/04_Appendice/01_More_on_infinite_trees/11_Infinite_Trees.lhs" class="cut">04_Appendice/01_More_on_infinite_trees/<strong>11_Infinite_Trees.lhs</strong></a></p>
<div style="display:none">
<p>This code is mostly the same as the preceding one.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb196"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb196-1" title="1"><span class="kw">import</span> <span class="dt">Debug.Trace</span> (trace)</a>
<a class="sourceLine" id="cb196-2" title="2"><span class="kw">import</span> <span class="dt">Data.List</span></a>
<a class="sourceLine" id="cb196-3" title="3"><span class="kw">data</span> <span class="dt">BinTree</span> a <span class="ot">=</span> <span class="dt">Empty</span> </a>
<a class="sourceLine" id="cb196-4" title="4"> <span class="op">|</span> <span class="dt">Node</span> a (<span class="dt">BinTree</span> a) (<span class="dt">BinTree</span> a) </a>
<a class="sourceLine" id="cb196-5" title="5"> <span class="kw">deriving</span> (<span class="dt">Eq</span>,<span class="dt">Ord</span>)</a></code></pre></div>
</div>
<div class="codehighlight">
<div class="sourceCode" id="cb197"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb197-1" title="1"><span class="co">-- declare BinTree a to be an instance of Show</span></a>
<a class="sourceLine" id="cb197-2" title="2"><span class="kw">instance</span> (<span class="dt">Show</span> a) <span class="ot">=&gt;</span> <span class="dt">Show</span> (<span class="dt">BinTree</span> a) <span class="kw">where</span></a>
<a class="sourceLine" id="cb197-3" title="3"> <span class="co">-- will start by a '&lt;' before the root</span></a>
<a class="sourceLine" id="cb197-4" title="4"> <span class="co">-- and put a : a begining of line</span></a>
<a class="sourceLine" id="cb197-5" title="5"> <span class="fu">show</span> t <span class="ot">=</span> <span class="st">&quot;&lt; &quot;</span> <span class="op">++</span> replace <span class="ch">'\n'</span> <span class="st">&quot;\n: &quot;</span> (treeshow <span class="st">&quot;&quot;</span> t)</a>
<a class="sourceLine" id="cb197-6" title="6"> <span class="kw">where</span></a>
<a class="sourceLine" id="cb197-7" title="7"> treeshow pref <span class="dt">Empty</span> <span class="ot">=</span> <span class="st">&quot;&quot;</span></a>
<a class="sourceLine" id="cb197-8" title="8"> treeshow pref (<span class="dt">Node</span> x <span class="dt">Empty</span> <span class="dt">Empty</span>) <span class="ot">=</span> </a>
<a class="sourceLine" id="cb197-9" title="9"> (pshow pref x)</a>
<a class="sourceLine" id="cb197-10" title="10"></a>
<a class="sourceLine" id="cb197-11" title="11"> treeshow pref (<span class="dt">Node</span> x left <span class="dt">Empty</span>) <span class="ot">=</span> </a>
<a class="sourceLine" id="cb197-12" title="12"> (pshow pref x) <span class="op">++</span> <span class="st">&quot;\n&quot;</span> <span class="op">++</span></a>
<a class="sourceLine" id="cb197-13" title="13"> (showSon pref <span class="st">&quot;`--&quot;</span> <span class="st">&quot; &quot;</span> left)</a>
<a class="sourceLine" id="cb197-14" title="14"></a>
<a class="sourceLine" id="cb197-15" title="15"> treeshow pref (<span class="dt">Node</span> x <span class="dt">Empty</span> right) <span class="ot">=</span> </a>
<a class="sourceLine" id="cb197-16" title="16"> (pshow pref x) <span class="op">++</span> <span class="st">&quot;\n&quot;</span> <span class="op">++</span></a>
<a class="sourceLine" id="cb197-17" title="17"> (showSon pref <span class="st">&quot;`--&quot;</span> <span class="st">&quot; &quot;</span> right)</a>
<a class="sourceLine" id="cb197-18" title="18"></a>
<a class="sourceLine" id="cb197-19" title="19"> treeshow pref (<span class="dt">Node</span> x left right) <span class="ot">=</span> </a>
<a class="sourceLine" id="cb197-20" title="20"> (pshow pref x) <span class="op">++</span> <span class="st">&quot;\n&quot;</span> <span class="op">++</span></a>
<a class="sourceLine" id="cb197-21" title="21"> (showSon pref <span class="st">&quot;|--&quot;</span> <span class="st">&quot;| &quot;</span> left) <span class="op">++</span> <span class="st">&quot;\n&quot;</span> <span class="op">++</span></a>
<a class="sourceLine" id="cb197-22" title="22"> (showSon pref <span class="st">&quot;`--&quot;</span> <span class="st">&quot; &quot;</span> right)</a>
<a class="sourceLine" id="cb197-23" title="23"></a>
<a class="sourceLine" id="cb197-24" title="24"> <span class="co">-- show a tree using some prefixes to make it nice</span></a>
<a class="sourceLine" id="cb197-25" title="25"> showSon pref before next t <span class="ot">=</span> </a>
<a class="sourceLine" id="cb197-26" title="26"> pref <span class="op">++</span> before <span class="op">++</span> treeshow (pref <span class="op">++</span> next) t</a>
<a class="sourceLine" id="cb197-27" title="27"></a>
<a class="sourceLine" id="cb197-28" title="28"> <span class="co">-- pshow replace &quot;\n&quot; by &quot;\n&quot;++pref</span></a>
<a class="sourceLine" id="cb197-29" title="29"> pshow pref x <span class="ot">=</span> replace <span class="ch">'\n'</span> (<span class="st">&quot;\n&quot;</span><span class="op">++</span>pref) (<span class="st">&quot; &quot;</span> <span class="op">++</span> <span class="fu">show</span> x)</a>
<a class="sourceLine" id="cb197-30" title="30"></a>
<a class="sourceLine" id="cb197-31" title="31"> <span class="co">-- replace on char by another string</span></a>
<a class="sourceLine" id="cb197-32" title="32"> replace c new string <span class="ot">=</span></a>
<a class="sourceLine" id="cb197-33" title="33"> <span class="fu">concatMap</span> (change c new) string</a>
<a class="sourceLine" id="cb197-34" title="34"> <span class="kw">where</span></a>
<a class="sourceLine" id="cb197-35" title="35"> change c new x </a>
<a class="sourceLine" id="cb197-36" title="36"> <span class="op">|</span> x <span class="op">==</span> c <span class="ot">=</span> new</a>
<a class="sourceLine" id="cb197-37" title="37"> <span class="op">|</span> <span class="fu">otherwise</span> <span class="ot">=</span> x<span class="op">:</span>[] <span class="co">-- &quot;x&quot;</span></a>
<a class="sourceLine" id="cb197-38" title="38"></a>
<a class="sourceLine" id="cb197-39" title="39">treeTakeDepth _ <span class="dt">Empty</span> <span class="ot">=</span> <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb197-40" title="40">treeTakeDepth <span class="dv">0</span> _ <span class="ot">=</span> <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb197-41" title="41">treeTakeDepth n (<span class="dt">Node</span> x left right) <span class="ot">=</span> <span class="kw">let</span></a>
<a class="sourceLine" id="cb197-42" title="42"> nl <span class="ot">=</span> treeTakeDepth (n<span class="op">-</span><span class="dv">1</span>) left</a>
<a class="sourceLine" id="cb197-43" title="43"> nr <span class="ot">=</span> treeTakeDepth (n<span class="op">-</span><span class="dv">1</span>) right</a>
<a class="sourceLine" id="cb197-44" title="44"> <span class="kw">in</span></a>
<a class="sourceLine" id="cb197-45" title="45"> <span class="dt">Node</span> x nl nr</a></code></pre></div>
</div>
</div>
<p>In order to resolve these problem we will modify slightly our <code>treeFromList</code> and <code>shuffle</code> function.</p>
<p>A first problem, is the lack of infinite different number in our implementation of <code>shuffle</code>. We generated only <code>4331</code> different numbers. To resolve this we make a slightly better <code>shuffle</code> function.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb198"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb198-1" title="1">shuffle <span class="ot">=</span> <span class="fu">map</span> rand [<span class="dv">1</span><span class="op">..</span>]</a>
<a class="sourceLine" id="cb198-2" title="2"> <span class="kw">where</span> </a>
<a class="sourceLine" id="cb198-3" title="3"> rand x <span class="ot">=</span> ((p x) <span class="ot">`mod`</span> (x<span class="op">+</span>c)) <span class="op">-</span> ((x<span class="op">+</span>c) <span class="ot">`div`</span> <span class="dv">2</span>)</a>
<a class="sourceLine" id="cb198-4" title="4"> p x <span class="ot">=</span> m<span class="op">*</span>x<span class="op">^</span><span class="dv">2</span> <span class="op">+</span> n<span class="op">*</span>x <span class="op">+</span> o <span class="co">-- some polynome</span></a>
<a class="sourceLine" id="cb198-5" title="5"> m <span class="ot">=</span> <span class="dv">3123</span> </a>
<a class="sourceLine" id="cb198-6" title="6"> n <span class="ot">=</span> <span class="dv">31</span></a>
<a class="sourceLine" id="cb198-7" title="7"> o <span class="ot">=</span> <span class="dv">7641</span></a>
<a class="sourceLine" id="cb198-8" title="8"> c <span class="ot">=</span> <span class="dv">1237</span></a></code></pre></div>
</div>
<p>This shuffle function has the property (hopefully) not to have an upper nor lower bound. But having a better shuffle list isnt enough not to enter an infinite loop.</p>
<p>Generally, we cannot decide whether <code>filter (&lt;x) xs</code> is empty. Then to resolve this problem, Ill authorize some error in the creation of our binary tree. This new version of code can create binary tree which dont have the following property for some of its nodes:</p>
<blockquote>
<p>Any element of the left (resp. right) branch must all be strictly inferior (resp. superior) to the label of the root.</p>
</blockquote>
<p>Remark it will remains <em>mostly</em> an ordered binary tree. Furthermore, by construction, each node value is unique in the tree.</p>
<p>Here is our new version of <code>treeFromList</code>. We simply have replaced <code>filter</code> by <code>safefilter</code>.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb199"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb199-1" title="1"><span class="ot">treeFromList ::</span> (<span class="dt">Ord</span> a, <span class="dt">Show</span> a) <span class="ot">=&gt;</span> [a] <span class="ot">-&gt;</span> <span class="dt">BinTree</span> a</a>
<a class="sourceLine" id="cb199-2" title="2">treeFromList [] <span class="ot">=</span> <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb199-3" title="3">treeFromList (x<span class="op">:</span>xs) <span class="ot">=</span> <span class="dt">Node</span> x left right</a>
<a class="sourceLine" id="cb199-4" title="4"> <span class="kw">where</span> </a>
<a class="sourceLine" id="cb199-5" title="5"> left <span class="ot">=</span> treeFromList <span class="op">$</span> safefilter (<span class="op">&lt;</span>x) xs</a>
<a class="sourceLine" id="cb199-6" title="6"> right <span class="ot">=</span> treeFromList <span class="op">$</span> safefilter (<span class="op">&gt;</span>x) xs</a></code></pre></div>
</div>
<p>This new function <code>safefilter</code> is almost equivalent to <code>filter</code> but dont enter infinite loop if the result is a finite list. If it cannot find an element for which the test is true after 10000 consecutive steps, then it considers to be the end of the search.</p>
<div class="codehighlight">
<div class="sourceCode" id="cb200"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb200-1" title="1"><span class="ot">safefilter ::</span> (a <span class="ot">-&gt;</span> <span class="dt">Bool</span>) <span class="ot">-&gt;</span> [a] <span class="ot">-&gt;</span> [a]</a>
<a class="sourceLine" id="cb200-2" title="2">safefilter f l <span class="ot">=</span> safefilter' f l nbTry</a>
<a class="sourceLine" id="cb200-3" title="3"> <span class="kw">where</span></a>
<a class="sourceLine" id="cb200-4" title="4"> nbTry <span class="ot">=</span> <span class="dv">10000</span></a>
<a class="sourceLine" id="cb200-5" title="5"> safefilter' _ _ <span class="dv">0</span> <span class="ot">=</span> []</a>
<a class="sourceLine" id="cb200-6" title="6"> safefilter' _ [] _ <span class="ot">=</span> []</a>
<a class="sourceLine" id="cb200-7" title="7"> safefilter' f (x<span class="op">:</span>xs) n <span class="ot">=</span> </a>
<a class="sourceLine" id="cb200-8" title="8"> <span class="kw">if</span> f x </a>
<a class="sourceLine" id="cb200-9" title="9"> <span class="kw">then</span> x <span class="op">:</span> safefilter' f xs nbTry </a>
<a class="sourceLine" id="cb200-10" title="10"> <span class="kw">else</span> safefilter' f xs (n<span class="op">-</span><span class="dv">1</span>) </a></code></pre></div>
</div>
<p>Now run the program and be happy:</p>
<div class="codehighlight">
<div class="sourceCode" id="cb201"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb201-1" title="1">main <span class="ot">=</span> <span class="kw">do</span></a>
<a class="sourceLine" id="cb201-2" title="2"> <span class="fu">putStrLn</span> <span class="st">&quot;take 10 shuffle&quot;</span></a>
<a class="sourceLine" id="cb201-3" title="3"> <span class="fu">print</span> <span class="op">$</span> <span class="fu">take</span> <span class="dv">10</span> shuffle</a>
<a class="sourceLine" id="cb201-4" title="4"> <span class="fu">putStrLn</span> <span class="st">&quot;\ntreeTakeDepth 8 (treeFromList shuffle)&quot;</span></a>
<a class="sourceLine" id="cb201-5" title="5"> <span class="fu">print</span> <span class="op">$</span> treeTakeDepth <span class="dv">8</span> (treeFromList <span class="op">$</span> shuffle)</a></code></pre></div>
</div>
<p>You should realize the time to print each value is different. This is because Haskell compute each value when it needs it. And in this case, this is when asked to print it on the screen.</p>
<p>Impressively enough, try to replace the depth from <code>8</code> to <code>100</code>. It will work without killing your RAM! The flow and the memory management is done naturally by Haskell.</p>
<p>Left as an exercise to the reader:</p>
<ul>
<li>Even with large constant value for <code>deep</code> and <code>nbTry</code>, it seems to work nicely. But in the worst case, it can be exponential. Create a worst case list to give as parameter to <code>treeFromList</code>.<br />
<em>hint</em>: think about (<code>[0,-1,-1,....,-1,1,-1,...,-1,1,...]</code>).</li>
<li>I first tried to implement <code>safefilter</code> as follow:
<pre>
safefilter' f l = if filter f (take 10000 l) == []
then []
else filter f l
</pre>
Explain why it doesnt work and can enter into an infinite loop.</li>
<li>Suppose that <code>shuffle</code> is real random list with growing bounds. If you study a bit this structure, youll discover that with probability 1, this structure is finite. Using the following code (suppose we could use <code>safefilter'</code> directly as if was not in the where of safefilter) find a definition of <code>f</code> such that with probability <code>1</code>, <code>treeFromList' shuffle</code> is infinite. And prove it. Disclaimer, this is only a conjecture.</li>
</ul>
<div class="sourceCode" id="cb202"><pre class="sourceCode haskell"><code class="sourceCode haskell"><a class="sourceLine" id="cb202-1" title="1">treeFromList' [] n <span class="ot">=</span> <span class="dt">Empty</span></a>
<a class="sourceLine" id="cb202-2" title="2">treeFromList' (x<span class="op">:</span>xs) n <span class="ot">=</span> <span class="dt">Node</span> x left right</a>
<a class="sourceLine" id="cb202-3" title="3"> <span class="kw">where</span></a>
<a class="sourceLine" id="cb202-4" title="4"> left <span class="ot">=</span> treeFromList' (safefilter' (<span class="op">&lt;</span>x) xs (f n)</a>
<a class="sourceLine" id="cb202-5" title="5"> right <span class="ot">=</span> treeFromList' (safefilter' (<span class="op">&gt;</span>x) xs (f n)</a>
<a class="sourceLine" id="cb202-6" title="6"> f <span class="ot">=</span> <span class="op">???</span></a></code></pre></div>
<p><a href="code/04_Appendice/01_More_on_infinite_trees/11_Infinite_Trees.lhs" class="cut">04_Appendice/01_More_on_infinite_trees/<strong>11_Infinite_Trees.lhs</strong> </a></p>
<h2 id="thanks">Thanks</h2>
<p>Thanks to <a href="http://reddit.com/r/haskell"><code>/r/haskell</code></a> and <a href="http://reddit.com/r/programming"><code>/r/programming</code></a>. Your comment were most than welcome.</p>
<p>Particularly, I want to thank <a href="https://github.com/Emm">Emm</a> a thousand times for the time he spent on correcting my English. Thank you man.</p>
<section class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Even if most recent languages try to hide them, they are present.<a href="#fnref1" class="footnote-back"></a></p></li>
<li id="fn2"><p>I know Im cheating. But I will talk about non-strictness later.<a href="#fnref2" class="footnote-back"></a></p></li>
<li id="fn3"><p>For the brave, a more complete explanation of pattern matching can be found <a href="http://www.cs.auckland.ac.nz/references/haskell/haskell-intro-html/patterns.html">here</a>.<a href="#fnref3" class="footnote-back"></a></p></li>
<li id="fn4"><p>Which is itself very similar to the javascript <code>eval</code> function, that is applied to a string containing JSON.<a href="#fnref4" class="footnote-back"></a></p></li>
<li id="fn5"><p>There are some <em>unsafe</em> exceptions to this rule. But you shouldnt see such use in a real application except maybe for debugging purposes.<a href="#fnref5" class="footnote-back"></a></p></li>
<li id="fn6"><p>For the curious ones, the real type is <code>data IO a = IO {unIO :: State# RealWorld -&gt; (# State# RealWorld, a #)}</code>. All the <code>#</code> has to do with optimisation and I swapped the fields in my example. But this is the basic idea.<a href="#fnref6" class="footnote-back"></a></p></li>
<li id="fn7"><p>Well, youll certainly need to practice a bit to get used to them and to understand when you can use them and create your own. But you already made a big step in this direction.<a href="#fnref7" class="footnote-back"></a></p></li>
</ol>
</section>
</div>
<div id="afterarticle">
<div id="social">
<a href="/rss.xml" target="_blank" rel="noopener noreferrer nofollow" class="social">RSS</a>
·
<a href="https://twitter.com/home?status=http%3A%2F%2Fyannesposito.com/Scratch/en/blog/Haskell-the-Hard-Way/%20via%20@yogsototh" target="_blank" rel="noopener noreferrer nofollow" class="social">Tweet</a>
·
<a href="http://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fyannesposito.com/Scratch/en/blog/Haskell-the-Hard-Way/" target="_blank" rel="noopener noreferrer nofollow" class="social">FB</a>
<br />
<a class="message" href="../../../../Scratch/en/blog/Social-link-the-right-way/">These social sharing links preserve your privacy</a>
</div>
<div id="navigation">
<a href="../../../../">Home</a>
<span class="sep">¦</span>
<a href="../../../../Scratch/en/blog">Blog</a>
<span class="sep">¦</span>
<a href="../../../../Scratch/en/softwares">Softwares</a>
<span class="sep">¦</span>
<a href="../../../../Scratch/en/about">About</a>
</div>
<div id="totop"><a href="#header">↑ Top ↑</a></div>
<div id="bottom">
<div>
Published on 2012-02-08
</div>
<div>
<a href="https://twitter.com/yogsototh">Follow @yogsototh</a>
</div>
<div>
<a rel="license" href="http://creativecommons.org/licenses/by/3.0/deed.en_US">Yann Esposito©</a>
</div>
<div>
Done with
<a href="http://www.vim.org" target="_blank" rel="noopener noreferrer nofollow"><strike>Vim</strike></a>
<a href="http://spacemacs.org" target="_blank" rel="noopener noreferrer nofollow">spacemacs</a>
<span class="pala">&amp;</span>
<a href="http://nanoc.ws" target="_blank" rel="noopener noreferrer nofollow"><strike>nanoc</strike></a>
<a href="http://jaspervdj.be/hakyll" target="_blank" rel="noopener noreferrer nofollow">Hakyll</a>
</div>
<hr />
<div style="max-width: 100%">
<a href="https://cardanohub.org">
<img src="../../../../Scratch/img/ada-logo.png" class="simple" style="height: 16px;
border-radius: 50%;
vertical-align:middle;
display:inline-block;" />
ADA:
</a>
<code style="display:inline-block;
word-wrap:break-word;
text-align: left;
vertical-align: top;
max-width: 85%;">
DdzFFzCqrhtAvdkmATx5Fm8NPJViDy85ZBw13p4XcNzVzvQg8e3vWLXq23JQWFxPEXK6Kvhaxxe7oJt4VMYHxpA2vtCFiP8fziohN6Yp
</code>
</div>
</div>
</div>
</div>
</div>
</body>
</html>