Note that there are some explanatory texts on larger screens.

plurals
  1. POIs is possible to improve type inference for partially applied types in Scala?
    text
    copied!<p>I'm trying to improve the type inference of the <code>traverse_</code> function in the code below:</p> <pre><code>import scala.language.higherKinds trait Applicative[AF[_]] { def ap[A, B](a: AF[A])(f: AF[A =&gt; B]): AF[B] def pure[A](a: A): AF[A] def fmap[A, B](a: AF[A])(f: A =&gt; B): AF[B] } def traverse_[AP[_]: Applicative, A](xs: Iterable[A])(f: A =&gt; AP[Unit]): AP[Unit] = { val ap = implicitly[Applicative[AP]] (xs :\ ap.pure(())) { (x, acc) =&gt; val apFunc = ap.fmap(f(x))(a =&gt; identity[Unit] _) ap.ap(acc)(apFunc) } } implicit def optionAp = new Applicative[Option] { def ap[A, B](a: Option[A])(f: Option[A =&gt; B]): Option[B] = f flatMap (a map _) def pure[A](a: A) = Some(a) def fmap[A, B](a: Option[A])(f: A =&gt; B) = a map f } implicit def eitherAp[L] = new Applicative[({type l[x]=Either[L, x]})#l] { def ap[A, B](a: Either[L, A])(f: Either[L, A =&gt; B]): Either[L, B] = f.right flatMap (a.right map _) def pure[A](a: A) = Right(a) def fmap[A, B](a: Either[L, A])(f: A =&gt; B) = a.right map f } // silly, but compiles val x = traverse_(1 to 10) { case 5 =&gt; None case _ =&gt; Some(()) } println(x) // also silly, but does not compile val y = traverse_(1 to 10) { case 5 =&gt; Left("x") case _ =&gt; Right(()) } println(y) </code></pre> <p>Running the above gives:</p> <pre><code>/Users/lodea/tmp/traverse.scala:49: error: no type parameters for method traverse_: (f: Int =&gt; AP[Unit])(implicit evidence$1: this.Applicative[AP])AP[Unit] exist so that it can be applied to arguments (Int =&gt; Product with Serializable with scala.util.Either[String,Unit]) --- because --- argument expression's type is not compatible with formal parameter type; found : Int =&gt; Product with Serializable with scala.util.Either[String,Unit] required: Int =&gt; ?AP val y = traverse_(1 to 10) { ^ /Users/lodea/tmp/traverse.scala:49: error: type mismatch; found : Int =&gt; Product with Serializable with scala.util.Either[String,Unit] required: Int =&gt; AP[Unit] val y = traverse_(1 to 10) { ^ two errors found </code></pre> <p>To get it to compile, I have to specify the type arguments to <code>traverse_</code>:</p> <pre><code>val y = traverse_[({type l[x]=Either[String, x]})#l, Int](1 to 10) { case 5 =&gt; Left("x") case _ =&gt; Right(()) } </code></pre> <p>Is there a way I can restructure <code>traverse_</code>, or any other part of the code, to make the type inference work? When the types start getting more complex, this gets annoying fast.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload