<img height="1" width="1" src="https://www.facebook.com/tr?id=1076094119157733&amp;ev=PageView &amp;noscript=1">

Merry Christmas

Posted by Jan Machacek on Thu, Dec 22, 2011

merrychristmas

import annotation.tailrec

abstract class Tree(val left: Tree) {
  def o = new Ball(this)
  def x = new Spike(this)
  def * = new Candle(this)
  def oxo = new BigBall(this)
  def oo = new DoubleBall(this)
  def *** = new ElectricCandle(this)

  def / = new LeftNeedle(this)
  def \ = new RightNeedle(this)
  def | = new Trunk(this)

}
class Top(star: Star) extends Tree(star)
abstract class Needle(left: Tree) extends Tree(left)
class LeftNeedle(left: Tree) extends Needle(left)
class RightNeedle(left: Tree) extends Needle(left) {

  def |||() {
    |||(true)
  }

  @tailrec
  final def |||(sparkle: Boolean) {
    val f = (t: Tree) =&gt;
      t match {
        case _: LeftNeedle =&gt; "/"
        case _: RightNeedle =&gt; "\\"
        case _: Trunk =&gt; "|"
        case _: Ball =&gt; "o"
        case _: Spike =&gt; "x"
        case _: Candle =&gt; "*"
        case _: BigBall =&gt; "oxo"
        case _: DoubleBall =&gt; "oo"
        case _: ElectricCandle =&gt; "***"
      }

    def walk(t: Tree, depth: Int): List[String] = {
      def walkLevel(t: Tree, acc: String,
                    f: (Tree) =&gt; String): (Tree, String) = {
        val fx = (t: Tree) =&gt; if (sparkle) f(t).toUpperCase else f(t)
        t match {
          case l: LeftNeedle =&gt; (l.left, fx(l) + "." + acc)
          case t: Tree =&gt; walkLevel(t.left, fx(t) + "." + acc, f)
        }
      }

      t match {
        case r: RightNeedle =&gt;
          val l = walkLevel(r, "", f)
          l._2 +: walk(l._1, depth + 1)
        case s: Star =&gt;
          List("--&gt;*&lt;-- ", "\\-/.")
      }
    }

    val tree = "||| " +: walk(this, 0)

    tree.reverse.foreach({l =&gt;
      val numSpaces = 30 - (l.length() / 2)
      val padding = " " * numSpaces
      print(padding)
      println(l)
    })

    Thread.sleep(500)

    |||(!sparkle)
  }

}
class Trunk(parent: Tree) extends Tree(parent)

abstract class Decoration(left: Tree) extends Tree(left)
class Star extends Decoration(null)
class Candle(left: Tree) extends Decoration(left)
class Ball(left: Tree) extends Decoration(left)
class Spike(left: Tree) extends Decoration(left)
class BigBall(left: Tree) extends Decoration(left)
class DoubleBall(left: Tree) extends Decoration(left)
class ElectricCandle(left: Tree) extends Decoration(left)

trait DecorationBuilder {
 def \-/ = new PartialDecoration
}
class PartialDecoration {
 def --&gt;*&lt;-- = new Star
}

object ChristmasTree extends DecorationBuilder {

  def main(args: Array[String]) {
           \-/.
         --&gt;*&lt;--
            .
           /.\
         ./.|.\.
         /.oxo.\
       ./.*.|.x.\.
       /.oo.|.oo.\
     ./.oxo.|.***.\.
     /.*.oo.|.*.oo.\.
           |||
  }

}

Recent Posts

Posts by Topic

see all

Subscribe to Email Updates