Skip to content

Instantly share code, notes, and snippets.

@shankarshastri
Created October 23, 2020 16:54
Show Gist options
  • Save shankarshastri/9e3a078eacdf95c8d7533b10c8499bf3 to your computer and use it in GitHub Desktop.
Save shankarshastri/9e3a078eacdf95c8d7533b10c8499bf3 to your computer and use it in GitHub Desktop.
ExploreIntersectionTypes
object ExploreIntersectionTypes {
trait Mapper[A, B] {
def map(l: List[A])(f: A => B): List[B] = l.map(f)
}
trait Reducer[A, B >: A] {
def reduce(l: List[A])(f: (B, B) => B): B = l.reduce(f)
}
def mapAndReduce[A, B, C >: B](mR: Mapper[A, B] & Reducer[B, C], l: List[A])(
mapFuncf: A => B
)(reduceFuncf: (C, C) => C): C = {
mR.reduce(mR.map(l)(mapFuncf))(reduceFuncf)
}
val multBy2: Int => Int = (e: Int) => e * 2
val reduceToSum: (Int, Int) => Int = (a: Int, b: Int) => (a + b)
case class MapperAndReducer[A, B, C >: B]()
extends Mapper[A, B]
with Reducer[B, C]
@main
def m: Unit = {
println(
mapAndReduce(MapperAndReducer[Int, Int, Int](), List(1, 2, 3))(multBy2)(
reduceToSum
)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment