Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit parameter in Scalaz

I try to find out why the call in scalaz.ListW.<^> works

def <^>[B: Zero](f: NonEmptyList[A] => B): B = value match {
  case Nil => ∅
  case h :: t => f(Scalaz.nel(h, t))
}

My minimal theory is:

trait X[T]{
   def y : T
}

object X{
  implicit object IntX extends X[Int]{
    def y = 42 
  }
  implicit object StringX extends X[String]{
    def y = "y" 
  } 
}
trait Xs{
  def ys[T](implicit x : X[T]) = x.y 
}

class A extends Xs{
  def z[B](implicit x : X[B]) : B = ys //the call ∅
}

Which produces:

import X._

scala> new A().z[Int]
res0: Int = 42

scala> new A().z[String]
res1: String = y

Is this valid? Can I achieve the same result with fewer steps?

like image 717
Thomas Jung Avatar asked Nov 14 '22 11:11

Thomas Jung


1 Answers

That's all there is to it. You could remove Xs and retain the essence of the example:

object A{
  def ys[T](implicit x : X[T]) = x.y 
}
A.ys

The other interesting aspect of the use in Scalaz is that the type argument to is inferred from the expected type B of the expression.

I recently had to change Zero to be invariant in its type parameter. This actually breaks the infer-ability of this type argument in some cases; you can see this in this example. There are a few related open tickets which will hopefully be solved by the changes on this branch.

like image 146
retronym Avatar answered Nov 17 '22 00:11

retronym