Skip to content

Commit

Permalink
optimize chain's get. (#2999)
Browse files Browse the repository at this point in the history
* optimize chain's get.

* add Chain#get spec.

* Switch to OpenJDK 8.
  • Loading branch information
tanaka takaya authored and kailuowang committed Aug 22, 2019
1 parent 48c8b34 commit 6db5193
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 3 deletions.
4 changes: 1 addition & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,13 @@ language: scala

sudo: required

dist: trusty

group: edge

git:
depth: 9999

jdk:
- oraclejdk8
- openjdk8

scala_version_211: &scala_version_211 2.11.12
scala_version_212: &scala_version_212 2.12.9
Expand Down
19 changes: 19 additions & 0 deletions core/src/main/scala/cats/data/Chain.scala
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,23 @@ sealed abstract class Chain[+A] {
else false

override def hashCode: Int = hash(Hash.fromUniversalHashCode[A])

final def get(idx: Long): Option[A] =
if (idx < 0) None
else {
var result: Option[A] = None
var i = 0L
foreachUntil { a =>
if (idx == i) {
result = Some(a)
true
} else {
i += 1
false
}
}
result
}
}

object Chain extends ChainInstances {
Expand Down Expand Up @@ -724,6 +741,8 @@ sealed abstract private[data] class ChainInstances extends ChainInstances1 {
go(f(a) :: Nil)
acc
}

override def get[A](fa: Chain[A])(idx: Long): Option[A] = fa.get(idx)
}

implicit def catsDataShowForChain[A](implicit A: Show[A]): Show[Chain[A]] =
Expand Down
3 changes: 3 additions & 0 deletions core/src/main/scala/cats/data/NonEmptyChain.scala
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,9 @@ sealed abstract private[data] class NonEmptyChainInstances extends NonEmptyChain
Eval.defer(fa.reduceRightTo(a => Eval.now(f(a))) { (a, b) =>
Eval.defer(g(a, b))
})

override def get[A](fa: NonEmptyChain[A])(idx: Long): Option[A] =
if (idx == 0) Some(fa.head) else fa.tail.get(idx - 1)
}

implicit def catsDataOrderForNonEmptyChain[A: Order]: Order[NonEmptyChain[A]] =
Expand Down
6 changes: 6 additions & 0 deletions tests/src/test/scala/cats/tests/ChainSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -254,4 +254,10 @@ class ChainSuite extends CatsSuite {
}
}

test("Chain#get is consistent with List#lift") {
forAll { (x: Chain[Int], idx: Int) =>
x.get(idx) should ===(x.toList.lift(idx))
}
}

}

0 comments on commit 6db5193

Please sign in to comment.