Skip to content

Commit

Permalink
Merge pull request #572 from smungee/feature/free-applicative-analyze
Browse files Browse the repository at this point in the history
Add FreeApplicative.analyze
  • Loading branch information
non committed Oct 16, 2015
2 parents cb804ce + e799fd0 commit 87c3fb3
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
7 changes: 7 additions & 0 deletions free/src/main/scala/cats/free/FreeApplicative.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cats
package free

import cats.arrow.NaturalTransformation
import cats.data.Const

/** Applicative Functor for Free */
sealed abstract class FreeApplicative[F[_], A] extends Product with Serializable { self =>
Expand Down Expand Up @@ -46,6 +47,12 @@ sealed abstract class FreeApplicative[F[_], A] extends Product with Serializable
}
}

/** Interpret this algebra into a Monoid */
def analyze[M:Monoid](f: F ~> λ[α => M]): M =
foldMap[Const[M, ?]](new (F ~> Const[M, ?]) {
def apply[X](x: F[X]): Const[M,X] = Const(f(x))
}).getConst

/** Compile this FreeApplicative algebra into a Free algebra. */
final def monad: Free[F, A] =
foldMap[Free[F, ?]] {
Expand Down
14 changes: 14 additions & 0 deletions free/src/test/scala/cats/free/FreeApplicativeTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package free
import cats.arrow.NaturalTransformation
import cats.laws.discipline.{ArbitraryK, ApplicativeTests, SerializableTests}
import cats.tests.CatsSuite
import cats.data.Const

import org.scalacheck.{Arbitrary, Gen}

Expand Down Expand Up @@ -75,4 +76,17 @@ class FreeApplicativeTests extends CatsSuite {
val fli2 = FreeApplicative.lift[List, Int](List(1, 3, 5, 7))
(fli1 |@| fli2).map(_ + _)
}

test("FreeApplicative#analyze") {
type G[A] = List[Int]
val countingNT = new NaturalTransformation[List, G] {
def apply[A](la: List[A]): G[A] = List(la.length)
}

val fli1 = FreeApplicative.lift[List, Int](List(1, 3, 5, 7))
fli1.analyze[G[Int]](countingNT) should === (List(4))

val fli2 = FreeApplicative.lift[List, Int](List.empty)
fli2.analyze[G[Int]](countingNT) should ===(List(0))
}
}

0 comments on commit 87c3fb3

Please sign in to comment.