typelevel / typelevel/cats

Convenient usage of isomorphisms

Open
#1,166 0 comments 0 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

Many times, writing the production and non-production code, I was having isomorphisms, but did not use it because of an absence of convenient syntax for it. Writing Iso.to(instance) defeats the purpose, especially for simple ones.

The idea is to provide implicit conversions to from and to, to be able to use isomorphic instances interchangeably.

If you agree, that it makes sense, I will do pull request for IsoConversions

The gist is:

import scala.language.implicitConversions

object IsoGist extends App {
  implicit val OMIso = new Iso[MyData, Option[String]] {
    override def to(a: MyData): Option[String] = a match {
      case NoDate => None
      case Data(x) => Some(x)
    }

    override def from(b: Option[String]): MyData = b match {
      case Some(t) => Data(t)
      case None => NoDate
    }
  }

  import isoConversions._

  val myData: MyData = Data("Hello")
  val someString: Option[String] = to(myData)

  val result = myData.flatMap(s => Option(s + " none"))

  println(result)  // prints Some(Hello none)


  def f1(z: MyData) = "just implementation"
  def f2(z: Option[String]) = "Just implementation"

  f1(someString)
  f2(myData)
}

trait Iso[A, B] {
  def to(a: A): B
  def from(b: B): A
}

object isoConversions {
  implicit def to[A, B](a: A)(implicit iso: Iso[A, B]): B = { iso to a }

  implicit def from[A, B](b: B)(implicit iso: Iso[A, B]): A = { iso from b }
}

sealed trait MyData
case object NoDate extends MyData
case class Data(a: String) extends MyData

(In the example we have MyData which is isomorphic to Option[String], and by providing conversions, we can interchangeably use them).

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

The issue names no repository files or tests. Start by reviewing the proposed Iso and isoConversions sketch, then inspect Cats' existing API conventions for implicit conversions. Done means an agreed design and an implementation with coverage for the shown interchangeable conversions.

Written by the indexing model from the issue text.

Assessment

Tech stack
scala
Domain
backend-api-design
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.