title: What is Just in Haskell and why wouldn't this function work without it?
body: <p>I have the following function that acts like an index operator:</p>
  
  <pre><code>let {
    index :: [a]-&gt;Int-&gt;Maybe a
    index [] i = error "Empty list"
    index l i = if i &lt;= ((length l) - 1) &amp;&amp; i &gt;= 0 then 
        Just(l !! i) 
      else
        error "Index out of bounds"
  }
  </code></pre>
  
  <p>Now, initially i wrote this without using <code>Just</code> (and i still don't understand what it is after googling):</p>
  
  <pre><code>let {
    index :: [a]-&gt;Int-&gt;Maybe a
    index [] i = error "Empty list"
    index l i = if i &lt;= ((length l) - 1) &amp;&amp; i &gt;= 0 then
        (l !! i) 
      else
        error "Index out of bounds"
  }
  </code></pre>
  
  <p>To me it the above function makes perfect sense. Because here i have a function that accepts a list of 'generic type' <code>a</code> and an <code>Int</code> which is the index and returns <code>Maybe</code> value of type <code>a</code> or throws runtime exception. However, i don't understand the bit where GHCi tells me this:</p>
  
  <pre><code>&lt;interactive&gt;:1:120:
  Couldn't match type `a' with `Maybe a'
    `a' is a rigid type variable bound by
        the type signature for index :: [a] -&gt; Int -&gt; Maybe a
        at &lt;interactive&gt;:1:34
  Expected type: [Maybe a]
    Actual type: [a]
  In the first argument of `(!!)', namely `l'
  In the expression: (l !! i)
  </code></pre>
  
  <p>Now, why is GHCi getting confused with the type of <code>l</code> and why is it expecting a list of type <code>Maybe a</code>? Finally, how does <code>Just</code> resolve the problem?</p>