Skip to content

Instantly share code, notes, and snippets.

@yllan
Created May 9, 2013 08:48
Show Gist options
  • Select an option

  • Save yllan/5546358 to your computer and use it in GitHub Desktop.

Select an option

Save yllan/5546358 to your computer and use it in GitHub Desktop.
Demonstrate how to implement append
sealed abstract class L[A] {
def append(l: L[A]): L[A]
}
case class LNil[A]() extends L[A] {
def append(l: L[A]) = l
override def toString = "Nil"
}
case class LCons[A](head: A, tail: L[A]) extends L[A] {
def append(l: L[A]): L[A] = LCons(head, tail.append(l))
override def toString = head.toString + " :: " + tail.toString
}
val l1 = LCons(1, LNil[Int])
val l2 = LCons(2, LCons(3, LNil[Int]))
val l3 = LCons(4, LCons(5, LCons(6, LNil[Int])))
println(l1) // 1 :: Nil
println(l2) // 2 :: 3 :: Nil
println(l3) // 4 :: 5 :: 6 :: Nil
println(l3.append(l2).append(l3)) // 4 :: 5 :: 6 :: 2 :: 3 :: 4 :: 5 :: 6 :: Nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment