Reputation: 3216
I'm trying to implement the functor and applicative instances for functions with the same initial type in Scala. My current implementation of the two type classes is:
trait Functor[F[_]] {
def fmap[A,B](f: A => B): F[A] => F[B]
}
trait Applicative[F[_]] extends Functor[F] {
def pure[A](a: A): F[A]
def apply[A,B](f: F[A => B]): F[A] => F[B]
}
The problem that I have is that Function1
has two type parameters and I think I cannot fix only one of them. Is it possible to do this in Scala?
Upvotes: 1
Views: 89
Reputation: 6132
One way to do it is with a type alias:
def FunctionFunctor[X] = {
type F[Y] = Function[X,Y]
new Functor[F] {
def fmap[A,B](f: A => B) = (fa: F[A]) => f.compose(fa)
}
}
Notice the def
, so you're creating a new functor instance for each specific X
type.
Other way to do is with type lambdas, which have a funny syntax:
def FunctionFunctor[X] = new Functor[({type F[Y] = Function[X,Y]})#F] {
def fmap[A,B](f: A => B) = (fa: Function[X,A]) => f.compose(fa)
}
Try and read about type lambdas, can be an obscure concept if you're not familiar with it. Good read about it is Scala in Depth
Upvotes: 3