Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
From @kaishh on functional programming Slack
// kaishh [4:20 AM]
// Found a neat way to always have typeclass syntax available without any wildcards imports:
package mypkg {
trait Functor[F[_]] {
def map[A, B](fa: F[A])(f: A => B): F[B]
}
final class FunctorOps[F[_], A](private val fa: F[A]) extends AnyVal {
def map[B](f: A => B)(implicit F: Functor[F]): F[B] = F.map(fa)(f)
}
}
package object mypkg {
/**
* Pun implicit conversion name to be the same as Functor –
* now importing Functor ALWAYS brings its syntax in scope
*/
implicit def Functor[F[_], A](fa: F[A]): FunctorOps[F, A] = new FunctorOps(fa)
}
package object user {
import mypkg.Functor
def increment[F[_]: Functor](l: F[Int]): F[Int] = {
l.map(_ + 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.