scalascalazscala-cats

value sequence is not a member of cats.Applicative[F]


I'm migrating some scalaz based code to typelevel cats.

project/plugins.sbt

addCompilerPlugin("org.typelevel" % "kind-projector" % "0.11.3" cross CrossVersion.full)

build.sbt

scalacOptions ++= Seq("-feature", "-deprecation", "-Xlint", "-Xfatal-warnings", "-Ypartial-unification")
scalaVersion := "2.12.10"

dependency in old scalaz based code is

libraryDependencies += "com.github.julien-truffaut" %%% "monocle-macro" % "1.4.8"

This is old scalaz-code based implementation which I want to migrate to cats.

import scalaz.Applicative
import scalaz.std.list._
import scalaz.syntax.applicative._
import scala.language.higherKinds
import monocle.PTraversal

def letterTraversal(predicate: Char ⇒ Boolean): PTraversal[String, String, Char, Char] = new PTraversal[String, String, Char, Char] {
         override def modifyF[F[_]: Applicative](f: Char ⇒ F[Char])(s: String): F[String] = {
           Applicative[F].sequence(s.toList map {
             case x if predicate(x) ⇒ f(x)
             case x ⇒ Applicative[F].point(x)
           }).map(_.mkString)
         }
     }

dependency in new code cats based code is

libraryDependencies += "com.github.julien-truffaut" %%% "monocle-macro" % "2.0.0"

This is my new code

import scala.language.higherKinds
import monocle.PTraversal
import cats.Applicative
import cats.implicits._

    def letterTraversal(predicate: Char ⇒ Boolean): PTraversal[String, String, Char, Char] = new PTraversal[String, String, Char, Char] {
            override def modifyF[F[_]: Applicative](f: Char ⇒ F[Char])(s: String): F[String] = {
              Applicative[F].sequence(s.toList map {
                case x if predicate(x) ⇒ f(x)
                case x ⇒ Applicative[F].point(x)
              }).map(_.mkString)
            }
        }
When I do `sbt clean compile` I get the below error -

[error] /Users/rajkumar.natarajan/Documents/Coding/OS/reftree/demo/jvm/src/main/scala/reftree/demo/Data.scala:07:22: value sequence is not a member of cats.Applicative[F]

[error] Applicative[F].sequence(s.toList map {

[error] ^ [error] one error found

[error] (demoJVM / Compile / compileIncremental) Compilation failed

[error] Total time: 32 s, completed May 27, 2021, 4:36:58 PM

Why I'm not getting the sequence function for Applicative[F] even though I added import cats.implicits._ in scope?


Solution

  • The idiomatic way to write that would be this:

    import cats.syntax.all._
    …
              s.toList.traverse {
                case x if predicate(x) ⇒ f(x)
                case x ⇒ x.pure[F]
              }.map(_.mkString)