Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

abstracting over type constructors

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 it also works with Option[Option[Option[T]]] or List[List[List[T]]] or any other combination of Option and List?

The following attempt obviously doesn't work, because types aren't 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 like that?

like image 874
fredoverflow Avatar asked Aug 25 '26 00:08

fredoverflow


1 Answers

Can you use Scalaz? If so this is pretty easy with the Each type class:

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("----------")
}
like image 59
Travis Brown Avatar answered Aug 27 '26 17:08

Travis Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!