Wednesday, July 13, 2011

A List containing elements with consecutive types A and B

Just wondering how we can create a "heterogenous" list of two types, where an object of the first type must be inserted after the second.

Examples:
5 :: "help" :: 8 :: "ldf" to create a list with type (Int, String)
 "help" :: 8 :: "ldf" :: 9 to create a list with type (String, Int)

Here is what I got:
class MyA[A, B](val head: A, val tail: Option[MyA[B, A]]) {
override def toString() = head + tail.map( "," + _.toString).getOrElse("")
def ::( x: B) = new MyA(x, Some(this))
}
object MyA {
def apply[A,B](value: A) : MyA[A, B] = new MyA(value, None)
}
// examples:
5 :: "help" :: 6 :: "kjl" :: 9 :: MyA("d") // 5,help,6,kjl,9,d
6:: "six" :: 7 :: "seven" :: 8 :: "eight" :: MyA(9) // 6,six,7,seven,8,eight,9
6:: "six" :: 7 :: "seven" :: "eight" :: MyA(9) // does not compile
view raw gistfile1.sbt hosted with ❤ by GitHub
Wondering if I can do better.

-