Type constructor abstraction

I have the following toy function:

def test[T](x: Option[List[Option[T]]])
{
    for (a <- x; b <- a; c <- b) println(c)
    println("----------")
}

How can I generalize the above function so that it also works with Option[Option[Option[T]]]or List[List[List[T]]]or with any other combination Optionand List?

The following attempt, obviously, does not work, because types are not type constructors:

def test2[Q,R,S,T](x: Q[R[S[T]]])

In C ++, I would probably use template templates for this purpose. Does Scala have something similar?

+3
source share
2 answers

Can you use Scalaz ? If it is so easy with the class Each:

import scalaz._, Scalaz._

def test[Q[_]: Each, R[_]: Each, S[_]: Each, T](x: Q[R[S[T]]]) {
  for (a <- x; b <- a; c <- b) println(c)
  println("----------")
}
+4
source

foreach, for-loop, . , , .

type E[V] = {def foreach[U](f: (V) => U)}
def test2[Q[R] <: E[R],R[S] <: E[S],S[T] <: E[T],T](x: Q[R[S[T]]]) {
  for (a <- x; b <- a; c <- b) println(c)
  println("----------")
}

:

scala> test2(List(List(List(8))))
8

scala> test2(Some(List(Some(8))))
8

for-loop , E, flatmap map-methods foreach.

+1

All Articles