Skip to content

Commit

Permalink
Add Iso involuton (#869)
Browse files Browse the repository at this point in the history
* Add Iso involuton + Corresponding tests

* Simplify comment block
  • Loading branch information
mlrv authored Jun 23, 2020
1 parent 4a0e784 commit e88b404
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
4 changes: 4 additions & 0 deletions core/shared/src/main/scala/monocle/Iso.scala
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,10 @@ object Iso {
/** alias for [[PIso]] id when S = T and A = B */
def id[S]: Iso[S, S] =
PIso.id[S, S]

/** create an [[Iso]] from a function that is its own inverse */
def involuted[A](update: A => A): Iso[A, A] =
Iso(update)(update)
}

sealed abstract class IsoInstances {
Expand Down
20 changes: 20 additions & 0 deletions test/shared/src/test/scala/monocle/IsoSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ class IsoSpec extends MonocleSuite {
implicit def emptyCaseTypeEq[A] = Eq.fromUniversalEquals[EmptyCaseType[A]]

val iso = Iso[IntWrapper, Int](_.i)(IntWrapper.apply)
val involutedListReverse =
Iso.involuted[List[Int]](_.reverse) // ∀ {T} -> List(ts: T*).reverse.reverse == List(ts: T*)
val involutedTwoMinusN = Iso.involuted[Int](2 - _) // ∀ {n : Int} -> n == 2 - (2 - n)

checkAll("apply Iso", IsoTests(iso))
checkAll("GenIso", IsoTests(GenIso[IntWrapper, Int]))
Expand All @@ -49,6 +52,9 @@ class IsoSpec extends MonocleSuite {

checkAll("Iso id", IsoTests(Iso.id[Int]))

checkAll("Iso involutedListReverse", IsoTests(involutedListReverse))
checkAll("Iso involutedTwoMinusN", IsoTests(involutedTwoMinusN))

checkAll("Iso.asLens", LensTests(iso.asLens))
checkAll("Iso.asPrism", PrismTests(iso.asPrism))
checkAll("Iso.asOptional", OptionalTests(iso.asOptional))
Expand Down Expand Up @@ -122,6 +128,20 @@ class IsoSpec extends MonocleSuite {
iso.modify(_ + 1)(IntWrapper(0)) shouldEqual IntWrapper(1)
}

test("involuted") {
involutedListReverse.get(List(1, 2, 3)) shouldEqual List(3, 2, 1)
involutedListReverse.reverseGet(List(1, 2, 3)) shouldEqual List(3, 2, 1)

involutedListReverse.reverse.get(List(1, 2, 3)) shouldEqual involutedListReverse.get(List(1, 2, 3))
involutedListReverse.reverse.reverseGet(List(1, 2, 3)) shouldEqual involutedListReverse.reverseGet(List(1, 2, 3))

involutedTwoMinusN.get(5) shouldEqual -3
involutedTwoMinusN.reverseGet(5) shouldEqual -3

involutedTwoMinusN.reverse.get(5) shouldEqual involutedTwoMinusN.get(5)
involutedTwoMinusN.reverse.reverseGet(5) shouldEqual involutedTwoMinusN.reverseGet(5)
}

test("GenIso nullary equality") {
GenIso.unit[Nullary] shouldEqual _nullary
}
Expand Down

0 comments on commit e88b404

Please sign in to comment.