Skip to content

Commit

Permalink
Implement QuicklensFunctor for Array (map[A, B] simplified to map[A])
Browse files Browse the repository at this point in the history
  • Loading branch information
OndrejSpanel committed Apr 28, 2022
1 parent 6c4c95e commit 56cc939
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.softwaremill
import scala.collection.{Factory, SortedMap}
import scala.annotation.compileTimeOnly
import com.softwaremill.quicklens.QuicklensMacros._
import scala.reflect.ClassTag

package object quicklens {

Expand Down Expand Up @@ -127,27 +128,33 @@ package object quicklens {
}

trait QuicklensFunctor[F[_]] {
def map[A, B](fa: F[A], f: A => B): F[B]
def map[A](fa: F[A], f: A => A): F[A]
def each[A](fa: F[A], f: A => A): F[A] = map(fa, f)
def eachWhere[A](fa: F[A], f: A => A, cond: A => Boolean): F[A] = map(fa, x => if cond(x) then f(x) else x)
}

object QuicklensFunctor {
given [S <: ([V] =>> Seq[V])]: QuicklensFunctor[S] with {
def map[A, B](fa: S[A], f: A => B): S[B] = fa.map(f).asInstanceOf[S[B]]
def map[A](fa: S[A], f: A => A): S[A] = fa.map(f).asInstanceOf[S[A]]
}

given QuicklensFunctor[Option] with {
def map[A, B](fa: Option[A], f: A => B): Option[B] = fa.map(f)
def map[A](fa: Option[A], f: A => A): Option[A] = fa.map(f)
}

given QuicklensFunctor[Array] with {
def map[A](fa: Array[A], f: A => A): Array[A] =
implicit val aClassTag: ClassTag[A] = fa.elemTag.asInstanceOf[ClassTag[A]]
fa.map(f)
}

given [K, M <: ([V] =>> Map[K, V])]: QuicklensFunctor[M] with {
def map[A, B](fa: M[A], f: A => B): M[B] = {
def map[A](fa: M[A], f: A => A): M[A] = {
val mapped = fa.view.mapValues(f)
(fa match {
case sfa: SortedMap[K, A] => sfa.sortedMapFactory.from(mapped)(using sfa.ordering)
case _ => mapped.to(fa.mapFactory)
}).asInstanceOf[M[B]]
}).asInstanceOf[M[A]]
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.softwaremill.quicklens
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.BeforeAndAfterEach
import org.scalatest.matchers.should.Matchers
import scala.reflect.ClassTag

class ModifyAllOptimizedTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach {
import ModifyAllOptimizedTest._
Expand Down Expand Up @@ -186,7 +187,7 @@ object ModifyAllOptimizedTest {
}

given QuicklensFunctor[Opt] with {
def map[A, B](fa: Opt[A], f: A => B): Opt[B] =
def map[A](fa: Opt[A], f: A => A): Opt[A] =
Opt.eachCount = Opt.eachCount + 1
fa match {
case Nada => Nada
Expand Down

0 comments on commit 56cc939

Please sign in to comment.