Created
January 14, 2021 22:23
-
-
Save dhinojosa/22b4d3e0b7f0c6cbfc6546d6bb4ec466 to your computer and use it in GitHub Desktop.
Higher Kinds and Functors in Scala 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.xyzcorp.demo.higherkindedtypes | |
trait Functor[F[_]]: | |
def fmap[A,B](fa:F[A])(f: A => B):F[B] | |
object Functor: | |
def apply[F[_]](using fun:Functor[F]):Functor[F] = fun | |
object ListTypeClasses: | |
given Functor[List] = | |
new Functor[List]: | |
def fmap[A,B](fa:List[A])(f:A => B) = | |
fa.map(f) | |
case class MyBox[A](value:A) | |
object MyBox: | |
given Functor[MyBox] = | |
new Functor[MyBox]: | |
def fmap[A,B](ba:MyBox[A])(f:A => B) = | |
new MyBox(f(ba.value)) | |
object EitherTypeClasses: | |
given Functor[[A] =>> Either[String,A]] = | |
new Functor[[A] =>> Either[String,A]]: | |
def fmap[A,B](se:Either[String,A])(f:A => B) = | |
se match | |
case Left(x) => Left(x) | |
case Right(y) => Right(f(y)) | |
object UsingHigherKindedTypes: | |
@main def assertUsingAHigherKindedTypeWorksWithList:Unit = | |
import ListTypeClasses.{given} | |
val result:List[Int] = Functor[List].fmap(List(1,2,3))(x => x * 2) | |
println(result) | |
@main def assertUsingAHigherKindedTypeWorksWithCustom:Unit = | |
import MyBox.{given} | |
val result:MyBox[Int] = Functor[MyBox].fmap(MyBox("Hello"))(x => x.length) | |
println(result) | |
@main def assertUsingWithAnEither:Unit = | |
import EitherTypeClasses.{given} | |
val result = Functor[[A] =>> Either[String,A]].fmap(Right(30))(x => x * 2) | |
println(result) | |
end UsingHigherKindedTypes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fun example! Here are some changes you might consider: