title: Haskell - creation of a monad
body: <p>I am trying to understand the rules of how to create a monad. As far as I understand, it depends on the data types that I want to use and that a monad has to fulfill three laws:</p>
  
  <pre><code>1. m &gt;&gt;= return = m
  2. return x &gt;&gt;= f = f x
  3. (m &gt;&gt;= f) &gt;&gt;= g = m &gt;&gt;= (\x-&gt; f x) &gt;&gt;= g
  </code></pre>
  
  <p>Okay. So for a monad <code>Maybe</code> I have the last 2 lines. For what does "<code>x</code>" stands in the third line. If should be a function, should it not?</p>
  
  <pre><code>data Maybe a = Nothing | Just a
  instance Monad Maybe where
    (Just x) &gt;&gt;= f = f x
    Nothing &gt;&gt;= _ = Nothing
    _ &gt;&gt;= x = x  
  
   fail _ = Nothing
  </code></pre>
  
  <p>(I am unable to find now the source of this definition, but I found it somewhere)</p>
  
  <p>I found another version as well - why do I need the line with "fail"?</p>
  
  <pre><code>data Maybe a = Nothing | Just a
  instance Monad Maube where
    return x = Just x
  
    Just x &gt;&gt;= f = f x
    Nothing &gt;&gt;= f = Nothing
  
    fail _ = Nothing
  </code></pre>
  
  <p>(source: <a href="http://learnyouahaskell.com/a-fistful-of-monads" rel="nofollow">http://learnyouahaskell.com/a-fistful-of-monads</a>)</p>