Created
April 6, 2013 10:41
-
-
Save akimichi/5325693 to your computer and use it in GitHub Desktop.
A rudimentary implementation of List collection in Scala.
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
describe("自前のListを定義する"){ | |
object test { | |
abstract class MyList[+T] { | |
def isEmpty: Boolean | |
def head: T | |
def tail: MyList[T] | |
def ::[U>:T](item: U): MyList[U] | |
} | |
case class MyListImpl[T](val head: T, val tail: MyList[T]) extends MyList[T] { | |
def ::[U>:T](item: U): MyList[U] = new MyListImpl(item, this) | |
def isEmpty = false | |
} | |
case object MyNil extends MyList[Nothing] { | |
def ::[U>:Nothing](item: U): MyList[U] = MyListImpl(item, MyNil) | |
override def isEmpty = true | |
def head: Nothing = throw new NoSuchElementException("no head in empty list") | |
def tail: MyList[Nothing] = throw new NoSuchElementException("no tail in empty list") | |
} | |
} | |
it("MyListを使う"){ | |
import test._ | |
val mylist = "ABC" :: "XYZ" :: "123" :: MyNil | |
mylist.head should equal("ABC") | |
mylist.tail should equal("XYZ" :: "123" :: MyNil) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment