Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add FreeApplicative.analyze #572

Merged
merged 1 commit into from
Oct 16, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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))
}
}