typelevel / typelevel/cats

Consider adding an InvariantMonad

Open
#2,160 4 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Scala
Stars
5.5k
Forks
1.2k
Avg merge
2d 10h
Merged PRs (30d)
5

Description

I came across the need for one recently and I think they can be fairly useful sometimes.
I've sketched out something based on @mpilquist's article


import cats._
import cats.implicits._

trait InvariantFlatMap[F[_]] extends InvariantSemigroupal[F] {

  def iflatMap[A, B](fa: F[A])(f: A => F[B])(g: B => A): F[B]
  
  override def product[A, B](fa: F[A], fb: F[B]): F[(A, B)] =
    iflatMap[A, (A, B)](fa)(a => imap[B, (A, B)](fb)(b => (a, b))(ab => ab._2))(ab => ab._1)
}

trait InvariantMonad[F[_]] extends InvariantMonoidal[F] with InvariantFlatMap[F] {
  def flatten[A](ffa: F[F[A]]): F[A] = iflatMap(ffa)(identity)(a => point(a))
  
  override def imap[A, B](fa: F[A])(f: A => B)(g: B => A): F[B] =
    iflatMap(fa)(a => point(f(a)))(g)
}

I think all of our current instances of InvariantMonoidal can also be InvariantMonads. I think it comes up enough to be useful in cats-core, but one could also envision this belonging into something like the proposed cats-more.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the existing InvariantMonoidal instances and the proposed InvariantFlatMap and InvariantMonad definitions in the issue. Check the cats-core typeclass hierarchy and current instance constraints before deciding whether the abstraction belongs there or in cats-more. Done means the API design and placement have been agreed and the relevant instances are covered.

Written by the indexing model from the issue text.

Assessment

Tech stack
scala
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.