Home
Reading
Searching
Subscribe
Sponsors
Statistics
Posting
Contact
Spam
Lists
Links
About
Hosting
Filtering
Features Download
Marketing
Archives
FAQ
Blog
 
Gmane
From: Vincent Cremet <vincent.cremet-Re5JQEeQqe8AvxtiuMwx3w <at> public.gmane.org>
Subject: Re: Variable typing
Newsgroups: gmane.comp.lang.scala.user
Date: Wednesday 11th July 2007 08:59:16 UTC (over 10 years ago)
> For a var, that would be difficult, because we cannot make var
> parametric. The best approximation is maybe
>
> scala> def bar[X] = (x:X) => foo(x)
> bar: [X](X) => X
>
> Maybe you are consoled by the fact that in the polymorphic
> lambda calculus, it would not be a problem to define *values*
> of such a type (bar is a *method* in Scala)
> [...]
> Burak

It is true that in Scala, methods can have polymorphic types but
values cannot. However, with type constructor polymorphism, I
think it is possible to encode values with polymorphic types. The
encoding relies on the following class.

  // Forall[A] = "forall X, A[X]"
  trait Forall[A[_]] { def Apply[X]: A[X] }

By definition, an instance of a polymorphic type "forall X, A[X]" must
provide a value of type "A[T]" for every type "T". We can check that
this is actually the case for an instance "x" of the Scala type
"Forall[A]": for every "T", "x.Apply[T]" is a value of type "A[T]".

As an example, we can define a value "f" that holds the polymorphic
function that returns the head of a list:

  // val f: [X] List[X] => X = [X] (xs: List[X]) => xs.head
  type A[X] = List[X] => X
  val f: Forall[A] = new Forall[A] {
    def Apply[X]: A[X] = (xs: List[X]) => xs.head
  }

Then, we can use "f" with different type instances:

  // val i: Int = f[Int](List(1,2))
  val i: Int = f.Apply[Int].apply(List(1,2))
  // val s: String = f[String](List("hello","world"))
  val s: String = f.Apply[String].apply(List("hello","world"))

Vincent
 
CD: 3ms