Created
May 9, 2013 08:48
-
-
Save yllan/5546358 to your computer and use it in GitHub Desktop.
Demonstrate how to implement append
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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