cats icon indicating copy to clipboard operation
cats copied to clipboard

Writer can be covariant?

Open windymelt opened this issue 1 year ago • 2 comments

I found Writer[L, V] is currently invariant.

https://github.com/typelevel/cats/blob/824b1cb2e77d9efd33ab3deb9b55e8bf1ce271c1/core/src/main/scala/cats/data/WriterT.scala#L28

Can it be covariant?

  • ZIO
    • This is not code itself, but they accepts treating Writer as covariant.
  • Scalaz
    • Currently not treating Writer as covariant.
  • Meanwhile, Reader[-R, A] is contra-variant on parameter R in Cats.

I'm newbie to contribute Cats, so any editing/closing is welcome.

Example that we want covariance for Writer

import cats.data.Writer
type Words[A] = Writer[List[String], A]

trait LongCat[F[_]]:
  def the: F["the"]
  def long(expr: F["the" | "long"]): F["long"]
  def cat(expr: F["long"]): F["cat"]
end LongCat

object LongCatImpl extends LongCat[Words]:
  def the: Words["the"] = Writer(List("the"), "the")
  def long(expr: Words["the" | "long"]): Words["long"] =
    expr.mapBoth((l, v) => ("long" :: l, "long"))
  def cat(expr: Words["long"]): Words["cat"] =
    expr.mapBoth((l, v) => ("cat" :: l, "cat"))
end LongCatImpl

locally:
  import LongCatImpl.*
  val repr = cat(long(long(the)))
  // => Found:    Words[("the" : String)]
  //    Required: Words[("the" : String) | ("long" : String)] 
  println(repr.run._1.reverse) // What I want: "the" :: "long" :: "long" :: "cat" :: Nil

windymelt avatar Jul 03 '24 14:07 windymelt

It can't be covariant, because we don't know anything about F[_]. We could require F[+_] which would allow it to be covariant, but that was not done.

that said, note that def widen[B >: A]: F[B] exists on Functor[F] and internally that can always be implemented by returning the same item (or at worst a safe cast due to the functor laws). So, you should be able to do fa.widen when you need covariance.

johnynek avatar Jul 27 '24 20:07 johnynek

Hey everyone, just to check the status: is there anything we are going to do with this draft?

satorg avatar Dec 05 '24 04:12 satorg