You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

2388 lines
227 KiB

<!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">Don’t 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 don’t 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, you’ll 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">
Don’t 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 won’t show you any Haskell super power. I will start with similarities between Haskell and other programming languages. Let’s 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, you’ll 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 won’t modify anything in the outside world. This means they can’t modify the value of a variable, can’t get user input, can’t write on the screen, can’t 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> doesn’t matter much if you don’t 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>Don’t 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. It’s not mandatory because the compiler is smart enough to discover it for you. It’s a good idea because it indicates intent and understanding.</p>
<p>Let’s 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> isn’t 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: don’t 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 don’t have to declare a new function for every single type. For example, in <code>C</code>, you’ll 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, let’s 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. It’s 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 shouldn’t 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 isn’t 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! It’s 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>Let’s 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, I’ll 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 don’t 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 won’t 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>Let’s 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 doesn’t 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 don’t understand what lazy and strict means, don’t 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 don’t 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> isn’t the easiest function to grasp. If you are not used to it, you should study it a bit.</p>
<p>To help you understand what’s going on here, let’s 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 didn’t 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 isn’t well suited to all usages. Or at least such a language hasn’t 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 doesn’t 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. Haskell’s 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 doesn’t 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. We’ll 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>We’ll 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, let’s 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 doesn’t 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. Don’t 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>