On Wed, Aug 10, 2011 at 6:14 PM, Brian Hurt <[email protected]> wrote:
> And what can I say about an element I've taken off a list of x-or-ys,
> say by using List.head? Without doing some sort of run time type
> identification, or having a type system that is complex enough to keep
> track of which elements in the list are xs and which are ys (which is
> a way more complicated type system than Ocaml, Haskell, or Scala-
> we're talking Coq, Twelf, or similar at this point).
It's actually fairly straightforward to define such types in Haskell
and Scala (and possibly OCaml, but I'm not sufficiently familiar with
OCaml to say either way with any confidence). Google for HList (for
"Heterogenous List").
Here's how it goes (in somewhat simplified form) in Scala,
trait HList
case class HCons[H, T <: HList](head : H, tail : T) extends HList {
def ::[T](v : T) = HCons(v, this)
override def toString = head+" :: "+tail.toString
}
class HNil extends HList {
def ::[T](v : T) = HCons(v, this)
override def toString = "HNil"
}
case object HNil extends HNil
type ::[H, T <: HList] = HCons[H, T]
val :: = HCons
And here's a sample session in the Scala REPL ... note how the element
type is tracked through calls to head and tail,
scala> val l = 1 :: true :: "foo" :: HNil
l: HCons[Int,HCons[Boolean,HCons[java.lang.String,HNil]]] =
1 :: true :: foo :: HNil
scala> l.head
res0: Int = 1
scala> l.tail.head
res1: Boolean = true
scala> l.tail.tail.head
res2: java.lang.String = foo
Cheers,
Miles
--
Miles Sabin
tel: +44 7813 944 528
gtalk: [email protected]
skype: milessabin
http://www.chuusai.com/
http://twitter.com/milessabin
--
You received this message because you are subscribed to the Google Groups "JVM
Languages" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/jvm-languages?hl=en.