Implementing functors in computer code.
Haskell Code
Code from here.
The 'Functor' class is used for types that can be mapped over. Instances of 'Functor' should satisfy the following laws:
- fmap id == id
- fmap (f . g) == fmap f . fmap g
class Functor f where fmap :: (a -> b) -> f a -> f b -- Replace all locations in the input with the same value. -- The default definition is @'fmap' . 'const'@, but this may be -- overridden with a more efficient version. (<$) :: a -> f b -> f a (<$) = fmap . const
Some Instances
The instances of 'Functor' satisfy these laws.
- fmap :: (a -> b) -> f a -> f b
List functor
instance Functor [] where fmap = map
IO functor
instance Functor ((->) r) where fmap = (.)
Maybe functor
instance Functor ((,) a) where fmap f (x,y) = (x, f y)
Scala Code
Code from here. package scalaz
Covariant function application in an environment. i.e. a covariant Functor.
All functor instances must satisfy 2 laws:
- identity
forall a. a == fmap(a, identity)
- composition
forall a f g. fmap(a, f compose g) == fmap(fmap(g, a), f)
trait Functor[F[_]] extends InvariantFunctor[F] { def fmap[A, B](r: F[A], f: A => B): F[B] final def xmap[A, B](ma: F[A], f: A => B, g: B => A) = fmap(ma, f) } object Functor { import Scalaz._ implicit def IdentityFunctor: Functor[Identity] = new Functor[Identity] { def fmap[A, B](r: Identity[A], f: A => B) = f(r.value) } implicit def TraversableFunctor[CC[X] <: collection.TraversableLike[X, CC[X]] : CanBuildAnySelf]: Functor[CC] = new Functor[CC] { def fmap[A, B](r: CC[A], f: A => B) = { implicit val cbf = implicitly[CanBuildAnySelf[CC]].builder[A, B] r map f } } implicit def NonEmptyListFunctor = new Functor[NonEmptyList] { def fmap[A, B](r: NonEmptyList[A], f: A => B) = r map f } implicit def ConstFunctor[BB: Monoid] = new Functor[({type λ[α]=Const[BB, α]})#λ] { def fmap[A, B](r: Const[BB, A], f: (A) => B) = Const(r.value) } implicit def StateFunctor[S] = new Functor[({type λ[α]=State[S, α]})#λ] { def fmap[A, B](r: State[S, A], f: A => B) = r map f }
Extending these examples to Natural Transformations
We can extend these examples to represent natural transformations as shown on page here.