Kevin Meredith
Kevin Meredith

Reputation: 41909

Using Context Bound with Higher Kinded Type?

Given:

scala> trait Functor[F[_]] { 
  def fmap[A, B](f: A => B, func: F[A]): F[B]
}

and then the something function:

scala> def something[A, B, F[_]](f: A => B, x: A)
                                (implicit ev: Functor[F]): F[B] = 
     |   ev.fmap(f, ???)
something: [A, B, F[_]](f: A => B, x: A)(implicit ev: Functor[F])F[B]

How could I re-write something using Context Bounds for the Functor rather than the implicit ev ... mechanism?

Upvotes: 0

Views: 152

Answers (1)

stew
stew

Reputation: 11366

def something[A, B, F[_]](f: A => B, x: A)
                          (implicit ev: Functor[F]): F[B] = 
    ev.fmap(f, ???)

can be rewritten as:

def something[A, B, F[_]: Functor](f: A => B, x: A): F[B] = 
    implicitly[Functor[F]].fmap(f, ???)

This is using the implicitly method from Predef which just asks for an implicit parameter and returns it:

def implicitly[A](implicit a: A): A = a

As an aside, As the other answer points out, you seem to be missing an F[A], which is perhaps why the second parameter to fmap is ???, you perhaps want x to be typed F[A], perhaps you want to change Functor to Applicative so that you can call ev.fmap(f, ev.point(x))

Upvotes: 4

Related Questions