Discover Snippets

@marcus marcus / FuncQS.scala Created at Mon May 14 04:23:16 EDT 2018
Functional quick-sort
// Functional quick-sort (not very effective)
// Example of pattern matching, for comprehension and recursion

def qs(list: List[Int]): List[Int] = list match {
case Nil => Nil
case x :: xs =>
lazy val ys = for (y <- xs if y <= x) yield y
lazy val zs = for (z <- xs if z > x) yield z
qs(ys) ++ List(x) ++ qs(zs)
}
@marcus marcus / GameOfLife.scala Created at Mon May 14 04:21:29 EDT 2018
Conway's Game of Life in Scala
object GameOfLife extends App {

case class Point(x: Int, y: Int)
type World = Set[Point]

val startingWorld = Set(Point(0, 0), Point(0, 1), Point(0, -1), Point(1, 0), Point(-1, 0))
allGenerations(startingWorld).take(10).map(worldToString).foreach(println)

def allGenerations(w: World) = Stream.iterate(w)(nextGeneration).takeWhile(_.nonEmpty)