Skip to content

Instantly share code, notes, and snippets.

@justinhj
Created July 16, 2019 15:49
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save justinhj/008b62a558e7fe7d947f53f38eb95fcd to your computer and use it in GitHub Desktop.
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