Slide 32
Slide 32 text
def sierpinskiTriangle(g: Graphics): IO[Unit] =
for
_ <- IO{ g.setColor(colour) }
_ <- sierpinskiTriangle(g, x, y, size)
yield ()
def sierpinskiTriangle(g:Graphics, x:Int, y:Int, size:Int):IO[Unit] =
if size <= minSize
then fillTriangle(g, x, y, size)
else
val halfSize = size / 2
for
_ <- sierpinskiTriangle(g, x, y, halfSize)
_ <- sierpinskiTriangle(g, x, y - halfSize, halfSize)
_ <- sierpinskiTriangle(g, x + halfSize, y, halfSize)
yield ()
def sierpinskiTriangle(g: Graphics): IO[Unit] =
List(
IO{ g.setColor(colour) },
sierpinskiTriangle(g, x, y, size)
).sequence_
def sierpinskiTriangle(g:Graphics, x:Int, y:Int, size:Int):IO[Unit] =
if size <= minSize
then fillTriangle(g, x, y, size)
else
val halfSize = size / 2
List(
sierpinskiTriangle(g, x, y, halfSize),
sierpinskiTriangle(g, x, y - halfSize, halfSize),
sierpinskiTriangle(g, x + halfSize, y, halfSize)
).sequence_
def sierpinskiTriangle(g: Graphics): IO[Unit] =
IO{ g.setColor(colour) } >> sierpinskiTriangle(g, x, y, size)
def sierpinskiTriangle(g:Graphics, x:Int, y:Int, size:Int):IO[Unit] =
if size <= minSize
then fillTriangle(g, x, y, size)
else
val halfSize = size / 2
sierpinskiTriangle(g, x, y, halfSize) >>
sierpinskiTriangle(g, x, y - halfSize, halfSize) >>
sierpinskiTriangle(g, x + halfSize, y, halfSize)
import cats.implicits._
putting actions in a list and sequencing
them using sequence_
sequencing actions using >>
sequencing actions using
a for comprehension
def sierpinskiTriangle(g: Graphics): IO[Unit] =
IO{ g.setColor(colour) } flatMap { _ =>
sierpinskiTriangle(g, x, y, size)
}
def sierpinskiTriangle(g:Graphics, x:Int, y:Int, size:Int):IO[Unit] =
if size <= minSize
then fillTriangle(g, x, y, size)
else
val halfSize = size / 2
sierpinskiTriangle(g, x, y, halfSize) flatMap { _ =>
sierpinskiTriangle(g, x, y - halfSize, halfSize) flatMap { _ =>
sierpinskiTriangle(g, x + halfSize, y, halfSize)
}
}
sequencing actions using flatMap