I am trying to find information if it is possible to create a Functor
for a Map
type.
The docs have information for the List
, Option
, but not for my case.
Can you please tell me if it is possible to create a Functor[Map[Int, T]]
?
Below I will attach an implementation of a similar functor for a List
.
trait Functor[F[_]]:
def map[A, B](list: F[A])(f: A => B): F[B]
given Functor[List] with
def map[A, B](list: List[A])(f: A => B): List[B] = ???
Map[A, B]
is almost the same as A => B
, but with a finite domain.A => B
is basically the Reader[A, B]
Reader[A, B]
is a monadSo, yes let's try to do the same as what Reader
does: it simply post-composes the functions given to map
:
given mapFunctor[K]: Functor[[V] =>> Map[K, V]] with
def map[A, B](m: Map[K, A])(f: A => B): Map[K, B] = m.view.mapValues(f).toMap
The toMap
is necessary, because mapValues
is non-strict (it refuses to map all the values right away, and keeps the function composition in a symbolic MapView
).