Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

optimize chain's get. #2999

Merged
merged 3 commits into from
Aug 22, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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))
}
}

}