项目作者: mtumilowicz

项目描述 :
Implementation of Const functor in Scala.
高级语言: Scala
项目地址: git://github.com/mtumilowicz/scala212-category-theory-const-functor.git


Build Status

scala212-category-theory-const-functor

Reference: https://bartoszmilewski.com/2015/01/20/functors/

preliminary

Referring my other github project could be useful
(basic info concerning functors):

discussion

When we think about functors we are not at all concerned
about accessing the values - it’s completely outside of
the formal scope of the functor. Functors are all about
being able to transforming underlying values with functions.

  • if there is possibility to access the values - we will
    see the transformed result
  • if we cannot access them - all we care is that the
    manipulations compose correctly and does not change
    anything when composed with identity

definition

Meaningful example of a functor that does not provide us
with an access to underlying values is a Const functor
that completely ignores its second argument:

  • data Const c a = Const c
  • map :: (a -> b) -> Const c a -> Const c b

The Const data type can be thought of similarly to the const function,
but as a data type.

project description

We will provide simple implementation of Const functor in Scala:

  1. final case class Const[C, A](param: C) {
  2. def map[B](f: A => B): Const[C, B] = this.asInstanceOf[Const[C, B]]
  3. }

and tests:

  • creation

    1. val const1: Const[Int, String] = Const(1)
    2. val const2: Const[Int, Object] = Const(1)
    3. const1.param should be(1)
    4. const2.param should be(1)
  • equals

    • same values, different dropped type

      1. val const1: Const[Int, String] = Const(1)
      2. val const2: Const[Int, Object] = Const(1)
      3. const1 should be(const2)
    • different values

      1. val const1: Const[Int, String] = Const(1)
      2. val const2: Const[Int, String] = Const(2)
      3. const1 should not be const2
    • map
      ```
      val const: Const[Int, Int] = Const(1)
  1. val mapped: Const[Int, String] = const.map(_ => "a")
  2. mapped.param should be(1)
  3. ```

Note that we provide the simplest implementation that there could be,
follow https://github.com/typelevel/cats/blob/master/core/src/main/scala/cats/data/Const.scala
to see much more sophisticated solution.