This page is no longer maintained — Please continue to the home page at www.scala-lang.org

trying to work with higher kinded types

1 reply
Ittay Dror 2
Joined: 2010-05-05,
User offline. Last seen 42 years 45 weeks ago.

scala> class Foo[AA[_] <: Traversable[_], BB[_] <: Traversable[_]] {
| def foo[A, B](xs: AA[A], f: A => B) =
| xs.map{f(_)}
| }
:34: error: type mismatch;
found : x$1.type (with underlying type _$1)
required: A
xs.map{f(_)}
^

(using 2.8.0 RC6)

What's wrong here?

Regards,

Ittay

Jason Zaugg
Joined: 2009-05-18,
User offline. Last seen 38 weeks 5 days ago.
Re: trying to work with higher kinded types

This is equivalent to:

class Foo[AA[X] <: Traversable[_$1] forSome { type _$1}]

The two uses of underscores have different meanings. The first is an
unnamed higher kinded type parameter, and the second is syntactic
sugar for an existential type.

Try this insead.

class Foo[AA[X] <: Traversable[X]] {
def foo[A, B](xs: AA[A], f: A => B): Traversable[B] = xs.map{f(_)}
}

If you want to return an AA[B] rather than Traverable[B], you need to
add an CanBuildFrom implicit parameter to foo:

import collection.generic.CanBuildFrom

class Foo[AA[X] <: Traversable[X]] {
def foo[A, B](xs: AA[A], f: A => B)(implicit cbf:
CanBuildFrom[AA[A], B, AA[B]]) : Traversable[B] = xs.map{f(_)}
}

You will also have a problem that Map is not a valid type argument for
the higher kinded parameter AA.

scala> new Foo[Seq]
res16: Foo[Seq] = Foo@115676d

scala> new Foo[Map]
:8: error: Map takes two type parameters, expected: one
new Foo[Map]

I've almost found a way around this [1], but it doesn't work as part
of an implicit view [2] [3].

-jason

[1] http://gist.github.com/445874
[2] https://lampsvn.epfl.ch/trac/scala/ticket/3201
[3] http://www.scala-lang.org/node/5677
-jason

On Tue, Jun 22, 2010 at 1:15 PM, Ittay Dror wrote:
>
>
> scala> class Foo[AA[_] <: Traversable[_], BB[_] <: Traversable[_]] {
>     |     def foo[A, B](xs: AA[A], f: A => B) =
>     |       xs.map{f(_)}
>     |   }
> :34: error: type mismatch;
>  found   : x$1.type (with underlying type _$1)
>  required: A
>             xs.map{f(_)}
>                      ^
>
>
> (using 2.8.0 RC6)
>
>
> What's wrong here?
>
>
> Regards,
>
> Ittay
>
>
>
>

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland