title: Trying to make sierpinski triangle generator in a functional programming style
body: <p>I have a function in Scala, and the same function in JavaScript, but I don't think it is in a functional style.</p>
  
  <pre><code>def drawSurroundingTriangles(startx : Double, starty : Double, width : Double) {
      var newwidth = width/2;
      var newstartx = startx + newwidth / 2;
      var newstarty = starty - newwidth;
      drawTriangle(newstartx, newstarty, newwidth);
      drawTriangle(newstartx - newwidth, starty + newwidth, newwidth);
      drawTriangle(newstartx + newwidth, starty + newwidth, newwidth);
      if(newwidth &lt; 6)
          return;
      drawSurroundingTriangles(newstartx, newstarty, newwidth);
      drawSurroundingTriangles(newstartx - newwidth, starty + newwidth, newwidth);
      drawSurroundingTriangles(newstartx + newwidth, starty + newwidth, newwidth);
  }
  </code></pre>
  
  <p>My hope is to have this be an iterator, rather than having it be recursive, so I can keep getting the next iteration, and it would print the next level, so my program initially creates the outer triangle, then draws the first inner triangle.  By making it an iterator I could wait for a key press to do the next iteration, perhaps changing colors each time.</p>
  
  <p>After that, it gets to this function, where it will loop, so on each iteration:</p>
  
  <ol>
  <li>Draw 3 triangles, one on each side
  of the central triangle</li>
  <li>Draw 9 triangles, one on each side
  of the three triangles from the
  previous iteration.</li>
  <li>Draw 27 triangles</li>
  </ol>
  
  <p>...</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>Sorry, I forgot a question mark, so it is hard to see the question.</p>
  
  <p>Basically, I would like to change it from a recursive function to one that I can call on demand, and have it draw the next iteration.  <strong>How can I do that?</strong></p>
  
  <p><strong>Update 2:</strong></p>
  
  <p>I have a solution that works, but I don't know which solution is better, mine or the one that is also an answer in this question:</p>
  
  <pre><code>def drawSurroundingTriangles(indexlist : List[(Double, Double, Double)]) : List[(Double, Double, Double)] = {
      var mylist = ListBuffer[(Double, Double, Double)]()
      indexlist.foreach{ 
          case (startx, starty, width) =&gt; { mylist ++ drawSingleTriangle(startx, starty, width) } }
  
      mylist.toList;
  }
  
  def drawSingleTriangle(startx : Double, starty : Double, width : Double) : List[(Double, Double, Double)] = {
      val newwidth = width/2;
      val newstartx = startx + newwidth / 2;
      val newstarty = starty - newwidth;
      var list = List((newstartx, newstarty, newwidth),
              ((newstartx - newwidth, starty + newwidth, newwidth)),
              (newstartx + newwidth, starty + newwidth, newwidth));
      list.foreach{ case (nstartx, nstarty, nwidth) =&gt; drawTriangle(nstartx, nstarty, nwidth)}
      list;
  }
  </code></pre>