-1

I'm trying to get my head around monads and Cats. Following some examples (e.g.cats) I wrote the code like below. But can't figure out how to make compiler to do what I need and to compile, actually.

import cats.Id
import cats.free.Free
import cats.~>

object Filtering extends App {

  sealed trait Filter[A]

  case class WhitespaceFilter(text: String) extends Filter[Seq[String]]

  case class LowerCaseFilter(strings: Seq[String]) extends Filter[Seq[String]]

  def whitespaceFilter(text: String): Free[Filter, Seq[String]] = Free.liftF(WhitespaceFilter(text))

  def lowerCaseFilter(strings: Seq[String]): Free[Filter, Seq[String]] = Free.liftF(LowerCaseFilter(strings))

  val process: (String => Free[Filter, Seq[String]]) = {
    text: String =>
      for {
        p1 <- whitespaceFilter(text)
        p2 <- lowerCaseFilter(p1)
      } yield p2
  }

  def compiler: Filter ~> Id  =
    new (Filter ~> Id) {
      def apply[A](fa: Filter[A]): Id[A] =
        fa match {
          // The code doesn't compile if uncommented...
          case WhitespaceFilter(text) => ??? // text.trim.split("""[\s]+""")
          case LowerCaseFilter(terms) => ??? // terms.map(_.toLowerCase)
        }
    }

  val result: Seq[String] = process("Some Text").foldMap(compiler)
  println(result) // should be Seq("some", "text")
}

Thanks!

kikulikov
  • 2,512
  • 4
  • 29
  • 45
  • Have you followed [the tutorial and example](http://typelevel.org/cats/datatypes/freemonad.html)? – Jasper-M May 12 '17 at 13:22
  • Yes, that is exactly what I followed. The same link is included in my question above. The problem is that the code doesn't compile when I uncomment those 2 lines... – kikulikov May 12 '17 at 20:16
  • At first glance I'd say you're missing the type alias. – Jasper-M May 12 '17 at 20:51
  • @Jasper-M I've just tried to run it with sbt and, surprisingly, it compiles fine. Apparently, it's `Intellij Idea` can't resolve types properly. It errors `Expression of type Array[String] doesn't conform to expected type cats.Id[A]`. Do you know how to make `Idea` happy? – kikulikov May 12 '17 at 21:03
  • No never used it. – Jasper-M May 13 '17 at 06:39

1 Answers1

1

I had a similar problem when playing around with the Cats example code you cited. I'm running IntelliJ IDEA and the IDE marks the commented lines with compiler errors but I can in fact run the code and get the output:

ArrayBuffer(some, text)

I think that IntelliJ's compiler is getting confused by the definition of Id:

type Id[A] = A

I'm not sure if IntelliJ uses it's own compiler or if it uses the Scala compiler. If the latter is true, there may be a way to get IntelliJ to use a more recent compiler that handles this type definition.

Good luck! :)

Tim Stewart
  • 5,350
  • 2
  • 30
  • 45