title: Turtle Graphics as a Haskell Monad
body: <p>I'm trying to implement <a href="https://en.wikipedia.org/wiki/Turtle_graphics">turtle graphics</a> in Haskell. The goal is to be able to write a function like this:</p>
  
  <pre><code>draw_something = do
      forward 100
      right 90
      forward 100
      ...
  </code></pre>
  
  <p>and then have it produce a list of points (maybe with additional properties):</p>
  
  <pre><code>&gt; draw_something (0,0) 0        -- start at (0,0) facing east (0 degrees)
  [(0,0), (0,100), (-100,100), ...]
  </code></pre>
  
  <p>I have all this working in a 'normal' way, but I've failed to implement it as a Haskell Monad and use the do-notation. The basic code:</p>
  
  <pre><code>data State a = State (a, a) a -- (x,y), angle
      deriving (Show, Eq)
  
  initstate :: State Float
  initstate = State (0.0,0.0) 0.0
  
  
  -- constrain angles to 0 to 2*pi
  fmod :: Float -&gt; Float
  fmod a 
      | a &gt;= 2*pi = fmod (a-2*pi)
      | a &lt;  0    = fmod (a+2*pi)
      | otherwise = a
  
  forward :: Float -&gt; State Float -&gt; [State Float]
  forward d (State (x,y) angle) = [State (x + d * (sin angle), y + d * (cos angle)) angle]
  
  right :: Float -&gt; State Float -&gt; [State Float]
  right d (State pos angle) = [State pos (fmod (angle+d))]
  
  
  bind :: [State a] -&gt; (State a -&gt; [State a]) -&gt; [State a]
  bind xs f = xs ++ (f (head $ reverse xs))
  
  ret :: State a -&gt; [State a]
  ret x = [x]
  </code></pre>
  
  <p>With this I can now write</p>
  
  <pre><code>&gt; [initstate] `bind` (forward 100) `bind` (right (pi/2)) `bind` (forward 100)
  [State (0.0,0.0) 0.0,State (0.0,100.0) 0.0,State (0.0,100.0) 1.5707964,State (100.0,99.99999) 1.5707964]
  </code></pre>
  
  <p>And get the expected result. However I can't make this an instance of <code>Monad</code>.</p>
  
  <pre><code>instance Monad [State] where
      ...
  </code></pre>
  
  <p>results in</p>
  
  <pre><code>`State' is not applied to enough type arguments
  Expected kind `*', but `State' has kind `* -&gt; *'
  In the instance declaration for `Monad [State]'
  </code></pre>
  
  <p>And if I wrap the list in a new object</p>
  
  <pre><code>data StateList a = StateList [State a]
  
  instance Monad StateList where
      return x = StateList [x]
  </code></pre>
  
  <p>I get</p>
  
  <pre><code>    Couldn't match type `a' with `State a'
        `a' is a rigid type variable bound by
          the type signature for return :: a -&gt; StateList a 
            at logo.hs:38:9
      In the expression: x        
      In the first argument of `StateList', namely `[x]'
      In the expression: StateList [x]
  </code></pre>
  
  <p>I tried various other versions but I never got it to run as I'd like to. What am I doing wrong? What do I understand incorrectly?</p>